!!!就当自己复习用好了
普通插槽
<div id="app">
<cpn>插槽内可以包含任何模板代码,包括HTML</cpn>
</div>
<template id='tpl'>
<div>
<h1>这里是子组件</h1>
<slot>默认内容</slot> <!-- 当父组件没有通过插槽传递内容的时候,默认显示该内容 -->
</div>
</template>
<script>
var vm = new Vue({
el: "#app",
components: {
cpn: {
template: '#tpl'
}
}
})
</script>
具名插槽
<div id="app">
<cpn>
<!--<template> 元素中的所有内容都将会被传入相应名字的插槽-->
<template v-slot:title>
<h1>title</h1>
</template>
<template v-slot:default>
<h1>content</h1>
</template>
</cpn>
</div>
<template id='tpl'>
<div>
<h1>这里是子组件</h1>
<slot name="title"></slot>
<slot></slot> <!-- name默认为default-->
</div>
</template>
<script>
var vm = new Vue({
el: "#app",
components: {
cpn: {
template: '#tpl'
}
}
})
</script>
作用域插槽(当父组件来决定子组件数据的展示方式时就用它)
- 父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。
- 因此父组件拿不到子组件的数据,只能通过将数据作为
<slot>元素的一个 attribute 绑定上去,让子组件的数据在父级的插槽内容中可用
<div id="app">
<cpn>
<!--使用带值的 v-slot 来定义我们提供的插槽 prop 的名字-->
<template v-slot:default="slotProps">
<p>{{ slotProps.user.userName }}</p>
<p>{{ slotProps.user.age }}</p>
</template>
</cpn>
</div>
<template id='tpl'>
<div>
<h1>这里是子组件</h1>
<!--绑定在 <slot> 元素上的 attribute 被称为插槽 prop-->
<slot v-bind:user="user"></slot>
</div>
</template>
<script>
var vm = new Vue({
el: "#app",
components: {
cpn: {
template: '#tpl',
data() {
return {
user: {
userName: '法外狂徒张三',
age: '28'
}
}
}
}
}
})
</script>