slot
//让我们子组件 在 不同父组件中 使用时,可以给这个组件的定义标签 添加内容,我们可以在子组件内部 得到你 在使用时 添加的内容,渲染出来
// 子组件内部 slot组件 代表了 子组件标签 嵌套的内容(相当于站为的作用)
<body>
<div id="app">
<home></home>
</div>
<script src="./vue.js"></script>
<script>
const Child = {
template: `
<div>
<slot></slot>
<h2>我是子组件</h2>
</div>
`
}
const Home = {//父组件
template:`
<div>
<child>
<div>//子组件中的slot标签内容
<button @click="fn">按钮</button>
<em>自定义内容</em>
</div>
</child>
</div>
`,
methods:{
fn(){
alert(1)
}
},
components: {
Child
}
}
Vue.component('Home', Home)
const vm = new Vue({
el: "#app"
})
</script>
</body>
这样做可以解决,在父组件中调用子组件不仅有子组件自己的内容 也有父组件给子组件自定义的可变的区域
新的问题,如呵给子组件插入多个自定义的内容
下面解决这个问题
在给子组件插入slot标签的时候起一个name属性名①,在父组件需要修饰的子组件内根标签加slot=“属性名①”
<script>
const Child = {
template: `
<div>
//接受
<slot name="a"></slot>//①
<h2>我是子组件</h2>
<slot name="b"></slot>//②
</div>
`
}
const Home = {//父组件
template:`
<div>
<child>
//定义
<div slot="a">//子组件中的slot标签内容①
<button @click="fn1">按钮1</button>
<em>自定义内容1</em>
</div>
<div slot="b">//子组件中的slot标签内容②
<button @click="fn2">按钮2</button>
<em>自定义内容2</em>
</div>
</child>
</div>
`,
methods:{
fn(){
alert(1)
}
},
components: {
Child
}
}