父控件 使用子控件时,为了能让子控件 在控件上面使用灵活多变,这里使用插槽。
- 简单插槽使用
<script>
// 创建 vue实例
const app = Vue.createApp({
data() {
return {
text: '提交'
}
},
// slot 插槽
// slot 中使用的数据,作用域的问题:
// 父模版里调用的数据属性,使用的都是父模版里的数据
// 子模版里调用的数据属性,使用的都是子模版里的数据
template: `
<myform>
<div>{{text}}</div>
</myform>
<myform>
<button>{{text}}</button>
</myform>
`
});
// 自定义组件 myform
app.component('myform', {
methods: {
addOne() {
alert(123)
},
},
// slot 无法绑定事件
// 解决方案 在 slot外层包裹 控件
// 解决 父组件往子组件 添加控件 使用dom
template: `
<div>
<input />
<span @click="addOne">
<slot></slot>
</span>
</div>
`
});
const vm = app.mount('#root');
</script>
- 插槽 作用域
为了让父控件灵活创建子控件
<script>
// 创建 vue实例
const app = Vue.createApp({
data() {
return {
text: '提交'
}
},
// 作用域插槽
template: `
<listView v-slot="slotProps">
<span>{{slotProps.item}}</span>
</listView>
`
});
// 自定义组件
app.component('listView', {
data() {
return{
list:[1,2,3],
}
},
template: `
<div>
<slot v-for="item in list" :item="item" />
</div>
`
});
const vm = app.mount('#root');
</script>
- 具名插槽使用
<script>
// 创建 vue实例
const app = Vue.createApp({
data() {
return {
text: '提交'
}
},
// 具名插槽
template: `
<myform>
<template v-slot:header>
<div>header</div>
</template>
<template v-slot:footer>
<div>footer</div>
</template>
</myform>
`
});
// 自定义组件
app.component('myform', {
// slot 无法绑定事件
// 解决方案 在 slot外层包裹 控件
// 解决 父组件往子组件 添加控件 使用dom
template: `
<div>
<slot name="header"></slot>
<div>content</div>
<slot name="footer"></slot>
</div>
`
});
const vm = app.mount('#root');
</script>
插槽使用简单介绍,更高级的使用后面会详细介绍。