详解Vue学习笔记入门篇之组件的内容分发(slot)(2)

在父级中,具有特殊属性 scope 的 <'template'> 元素必须存在,表示它是作用域插槽的模板。scope 的值对应一个临时变量名,此变量接收从子组件中传递的 props 对象。

作用域插槽更具代表性的用例是列表组件,允许组件自定义应该如何渲染列表每一项:

<div> <my-component :items="items"> <template slot="item" scope="props"> <li>{{props.text}}</li> </template> </my-component> </div>

Vue.component('my-component',{ template:` <ul> <slot v-for="item in items" :text="item.text"></slot> </ul> `, props:['text','items'] }) new Vue({ el:'#app', data:{ items:[ {text:'item1'}, {text:'item2'}, {text:'item3'}, ] } })

作用域插槽也可以是具名的

运行结果:

详解Vue学习笔记入门篇之组件的内容分发(slot)

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyjxgd.html