slot 插槽
- 作用/概念: 预先将将来要使用的内容进行保留
- 具名插槽: 给slot起个名字
-
注意: 以上两种形式在 vue2.6以上被废弃
-
为什么要 用 v-slot指令来代替呢?
- 经具名插槽和作用域插槽进行统一
- 要将这两个属性带有 vue的标志,并且符合vue两个最大的特性之一: 指令的概念
-
要求: 2.6版本前的会,2.6版本后的v-slot也得会
插槽案例1:
<div id="app">
<Hello>
<div>
这里是1903
</div>
</Hello>
</div>
<template id="hello">
<div>
<slot></slot>
<h3>这里是hello</h3>
</div>
</template>
Vue.component('Hello',{
template: '#hello'
})
new Vue({
el: '#app'
})
插槽案例2:
<div id="app">
<Hello>
<header slot = 'header'> 这里是头部 </header>
<footer slot = 'footer'> 这里是底部 </footer>
</Hello>
</div>
<template id="hello">
<div>
<slot name = "header"></slot>
<h3>这里是hello</h3>
<slot name = "footer"></slot>
</div>
</template>
Vue.component('Hello',{
template: '#hello'
})
new Vue({
el: '#app'
})
插槽案例3:
<div id="app">
<Hello>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</Hello>
</div>
<template id ='hello'>
<div class="container">
<header>
<!-- 我们希望把页头放这里 -->
<slot name = "header"></slot>
</header>
<main>
<!-- 我们希望把主要内容放这里 -->
</main>
<footer>
<!-- 我们希望把页脚放这里 -->
<slot name = 'footer'></slot>
</footer>
</div>
</template>
Vue.component('Hello',{
template: '#hello'
})
new Vue({
el: '#app',
data: {
msg: '<h3> hello 1903</h3>'
}
})
slot 作用域插槽
-
旧: slot-scope
- 使用流程
- 在组件的模板中书写slot插槽,并将当前组件的数据通过 v-bind 绑定在 slot标签上
- 在组件使用时,通过slot-scope = “slotProp” 来接收slot标签身上绑定的数据
- 通过 slotProp.xxx 就可以进行使用了
<div id="app"> <Hello> <template slot = "default" slot-scope = "slotProp"> <p> {{ slotProp.msg }} </p> </template> </Hello> </div> <template id="hello"> <div> <slot name = "default" :msg = "msg"></slot> </div> </template>
Vue.component('Hello',{ template: '#hello', data () { return { msg: 'hello' } } }) new Vue({ el: '#app' })
- 使用流程
-
新: v-slot
<div id="app">
<Hello>
<template v-slot:default = "slotProp">
{{ slotProp.msg }}
</template>
</Hello>
</div>
<template id="hello">
<div>
<slot name = "default" :msg = "msg"></slot>
</div>
</template>
new Vue({
components: {
'Hello': {
template: '#hello',
data () {
return {
msg: 'hello'
}
}
}
}
}).$mount('#app')