slot: 位置;狭槽;水沟;硬币投币口 ---from有道词典
个人理解为位置预占, 有新增则覆盖, 无则显示预占内容
一、 默认情况
<template>
<div id='app'>
<children>
<span> i am tangerine </span>
</children>
</div>
</template>
<script>
import Vue from 'vue';
new Vue({
components: {
children: { template: '<p> i am children </p>' }
}
}).$mount('#app')
</script>
此时 <span> i am tangerine </span> 不会显示 由于children组件中并未设置插槽。
二、单个slot
<template>
<div id='app'>
<children>
<span> i am tangerine </span>
</children>
</div>
</template>
<script>
import Vue from 'vue';
new Vue({
components: {
children: { template: '<p> i am children<slot><span> i am slot without name </span></slot> </p>' }
}
}).$mount('#app')
</script>
此时<span> i am tangerine </span>将替换<slot>整个标签进行渲染 如果无<span> i am tangerine </span>将会显示默认内容<span> i am slot without name </span>
二、具名slot
<template>
<div id='app'>
<children>
<span slot="firstSlot"> i am tangerine </span>
<span> who am i ? </span>
<span slot="secondSlot"> i am apple </span>
<span> who are you ? </span>
<span slot="firstSlot"> i am orange </span>
</children>
</div>
</template>
<script>
import Vue from 'vue';
new Vue({
components: {
children: { template: '<p> i am children<slot name="firstSlot"><span> i am slot one </span></slot><slot name="secondSlot"><span> i am slot two </span></slot><slot></slot> </p>' }
}
}).$mount('#app')
</script>
经测试多个相同slot名的元素将依次插入对应的预占位置,无slot名的元素依次插入无name值的slot位置,即表现为<p> i am children<span> i am tangerine </span><span> i am orange </span><span> i am apple </span><span> who am i ? </span><span> who are you ? </span></p>
三、实例
一个具有默认显示的<Alert>组件
当我们想要有 Success、Warning、Error 等不同样式和不同内容的 alert 时,我们会希望这样使用:
<Alert type="success">
<strong>success: </strong> this is some info about success;
</Alert>
<Alert type="wraning">
<strong>wraning: </strong> this is some info about wraning;
</Alert>
<Alert type="error">
<strong>error: </strong> this is some info about error;
</Alert>
要实现这个功能 具体如下:
Alert.js
<template>
<div :class="typeClass">
<slot><strong>default: </strong> this is some info about default; </slot>
</div>
</template>
<script>
import Vue from 'vue';
export default Vue.extend({
props: [ 'type' ],
computed: {
typeClass()
{
return `${ this.type||'default' }-alert`
}
}
})
</script>
<style scoped>
.success-alert{}
.error-alert{}
.wraning-alert{}
.default-alert{}
</style>
app.js
<template>
<div id="app">
<Alert></Alert>
<Alert type="success"> status_success </Alert>
<div>
</template>
<script>
import Vue from 'vue';
import Alert from 'Alert';
new Vue({
components: { Alert }
}).$mount('#app')
</script>
四、进阶 - 结合render函数
预知后事如何,且听下回分解
网友评论