用来访问被插槽分发的内容。每个具名插槽有其相应的
property(例如:v-slot:foo中的内容将会在vm.$slots.foo中被找到)。default property包括了所有没有被包含在具名插槽中的节点,或v-slot:default的内容。
请注意插槽不是响应性的。如果你需要一个组件可以在被传入的数据发生变化时重渲染,我们建议改变策略,依赖诸如props或data等响应性实例选项。
注意:v-slot:foo在2.6以上的版本才支持。对于之前的版本,你可以使用废弃了的语法。在使用渲染函数书写一个组件时,访问
vm.$slots最有帮助。
v-slot指令自Vue 2.6.0起被引入,提供更好的支持slot 和 slot-scope attribute 的 API替代方案。v-slot完整的由来参见这份RFC。在接下来所有的 2.x 版本中slot和slot-scope attribute仍会被支持,但已经被官方废弃且不会出现在Vue 3中。
html
<!-- 在表达式中使用 ES2015 解构 -->
<todo-list v-bind:todos="todos">
<template slot="operation" slot-scope="{ todo }">
<span v-if="todo.isComplete">✓</span>
{{ todo.text }}
</template>
<template slot="default" slot-scope="slotProps">
{{ slotProps.msg }}
</template>
</todo-list>
html
<todo-list v-bind:todos="todos">
<template v-slot:operation="{ todu }" >
<span v-if="todo.isComplete">✓</span>
{{ todo.text }}
</template>
<template v-slot:default="slotProps">
{{ slotProps.msg }}
</template>
</todo-list>
javascript
Vue.component('blog-post', {
render: function (createElement) {
var header = this.$slots.header
var body = this.$slots.default
var footer = this.$slots.footer
return createElement('div', [
createElement('header', header),
createElement('main', body),
createElement('footer', footer)
])
}
})
v-slot:other="otherSlotProps"这样的语法来将数据传递给插槽
ChildComponent 的模板代码:
html
<template>
<div>
<slot name="other" :otherSlotProps="otherSlotProps"></slot>
</div>
</template>
<script>
export default {
data() {
return {
otherSlotProps: {
message: 'Hello from parent component'
}
};
}
};
</script>
ParentComponent 的模板代码:
html
<template>
<div>
<ChildComponent>
<template v-slot:other="otherSlotProps">
<p>{{ otherSlotProps.message }}</p>
</template>
</ChildComponent>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
}
};
</script>