1.插槽
了解插槽的使用之前,首先要了解组件,插槽可以用来合成组件,父组件可以很灵活的修改子组件的内容。
2.标签用法
custom-input组件中的内容会替代模板中slot标签的内容,
<div id="app">
<custom-input>
vue
</custom-input>
</div>
<script>
Vue.component("custom-input",
{
props:['value'],
template:`<div>hello,
<slot></slot>
</div>`
});
var app11 = new Vue({
el:'#app',
data:{
searchText:''
}
})
3.后备内容
slot中间可以添加内容,作为默认内容,如果组件没有添加内容,它将作为默认显示
<div id="app">
<custom-input :name="name">
</custom-input>
<custom-input :name="name">
vue
</custom-input>
</div>
<script>
Vue.component("custom-input",
{
props:['name'],
template:`<div>hello,
<slot>{{name}}</slot>
</div>`
});
var app11 = new Vue({
el:'#app',
data:{
name:'ly'
}
})
4.具名插槽
在组件模板的定义中,我们可以为slot标签的name属性赋值,在调用组件时,配合template标签和v-slot属性将值赋予对应的插槽,如果没有被tempate和v-slot包裹的元素,将会被传入默认的插槽。
<div id="app">
<custom-input>
<template v-slot:header>
<div>header</div>
</template>
<div>default slot content</div>
<template v-slot:footer>
<div>footer</div>
</template>
</custom-input>
</div>
<script>
Vue.component("custom-input",
{
template:`,
<div>
<slot name="header"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>`
});
var app11 = new Vue({
el:'#app',
data:{
name:'ly'
}
})
</script>
5.作用域插槽
作用域插槽能让插槽内容能访问子组件中的数据,数据在各自的具名插槽中,用v-bind绑定到插槽中,在template元素上,我们在原先的具名插槽上将值赋予一个对象,通过对象,可以访问绑定在插槽上对应的属性
例如:v-slot:header=“header”
<div id="app">
<custom-input >
<template v-slot:header="header">
<p>my name is {{header.user.name}}</p>
</template>
<template v-slot:default="slotProps">
<p>my age is {{slotProps.user.age}}</p>
</template>
</custom-input>
</div>
<script>
Vue.component("custom-input",
{
template:`
<div>
<slot name="header" v-bind:user="user">
</slot>
<slot v-bind:user="user">
</slot>
</div>`,
data:function(){
return {
user:{
name:'ly',
age:24,
address:'shenzhen'
}
}
}
});
var app11 = new Vue({
el:'#app',
data:{
}
})
</script>