普通页面元素是有属性和内容的,在vue中我们通过prop让组件拥有了属性,那么这篇内容我们来了解一下怎么给组件添加内容
默认插槽
<div id="app">
<post-item>控件的值是通过组件的插槽传递过去的</post-item>
</div>
<script>
Vue.component('PostItem', {
template: '<h3><slot></slot></h3>'
})
let vm = new Vue({
el: "#app",
})
</script>
在上述案例中,组件模板中<h3>元素中使用了一个 <slot>
元素,这个元素就是插槽,也可以理解为占位符。在父组件中给这个占位符添加内容,就出现了下列效果
插槽的作用域和插槽的默认值
<div id="app">
<!-- <post-item>控件的值是通过组件的插槽传递过去的</post-item> -->
<post-item></post-item>
<post-item>{{ val }}</post-item>
</div>
<script>
Vue.component('PostItem', {
template: '<h3><slot>这个是插槽的默认值</slot></h3>'
})
let vm = new Vue({
el: "#app",
data: {
val: '这个是通过插槽动态传递过去的'
}
})
</script>
如果通过插槽动态传递参数,动态参数是在父组件的作用域下解析的,而不是在子组件的作用域。除了动态传递参数,还可以给插槽定义一个默认参数。
命名插槽
在组件中,可以会使用到多个插槽,所以可以给插槽进行命名。
<div id="app">
<post-item>
<template v-slot:item1>这个是通过命名插槽item1传递的</template>
<template v-slot:default>这个是通过默认插槽传递的</template>
<template #item2>这个是通过命名插槽item2传递的,这个v-slot指令是缩写语法</template>
</post-item>
</div>
<script>
Vue.component('PostItem', {
template: `<div>
<slot name='item1'></slot></br>
<slot></slot></br>
<slot name='item2'></slot>
</div>`
});
let vm = new Vue({
el: "#app",
})
</script>
在组件中给<slot>
元素添加name
属性来给插槽命名,在使用组件的时候通过给<template>
元素添加v-slot
指令。如果是不对插槽进行命名,则表示为默认插槽,默认插槽可以不使用<template>
元素,也可以通过给<template>
元素添加v-slot:default或v-slot。
v-slot指令只能在<template>
元素或组件上使用,且可以通过#
替换v-slot