vue插槽slot
vue提供的插槽听起来有点抽象,实际上就是在组件模板中添加一个或多个的槽标签<slot></slot>,该槽标签是用于被其他组件给替换的,话不多说,看下面的例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=<device-width>, initial-scale=1.0"> <script crossorigin="anonymous" integrity="sha512-BKbSR+cfyxLdMAsE0naLReFSLg8/pjbgfxHh/k/kUC82Hy7r6HtR5hLhobaln2gcTvzkyyehrdREdjpsQwy2Jw==" src="https://lib.baomitu.com/vue/2.6.12/vue.min.js"></script> <title>Document</title> </head> <body> <!-- view --> <div id="app"> <one> <two slot="first"></two> <three slot="second"></three> </one> </div> <!-- viewmodel --> <script> //one 组件 Vue.component("one",{ template: '<div>\ <slot name="first"></slot>\ <ul>\ <slot name="second"></slot>\ </ul>\ </div>' }); //two 组件 Vue.component("two",{ template: '<div>第一个槽被我占了</div>' }) //three 组件 Vue.component("three",{ template: '<li>第二个槽被我占了</li>' }) var vm = new Vue({ el:"#app", data:{ message:"" } }); </script> </body> </html>
现在来解释下上面的代码,有3个组件,分别是:one,two,three,one组件中留有两个槽<slot>,用于被two和three两个组件插入的;
在one组件的template中,我们需要给<slot>设置name属性用于标识该槽,然后我们组件,比如two,可以设置slot属性,这个属性是用来指定要插入到哪一个槽中的。
下面是复杂点的:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=<device-width>, initial-scale=1.0"> <script crossorigin="anonymous" integrity="sha512-BKbSR+cfyxLdMAsE0naLReFSLg8/pjbgfxHh/k/kUC82Hy7r6HtR5hLhobaln2gcTvzkyyehrdREdjpsQwy2Jw==" src="https://lib.baomitu.com/vue/2.6.12/vue.min.js"></script> <title>Document</title> </head> <body> <!-- view --> <div id="app"> <one> <two slot="first" :name="username"></two> <three slot="second" :age="a" v-for="a in allages"></three> </one> </div> <!-- viewmodel --> <script> //one 组件 Vue.component("one",{ template: '<div>\ <slot name="first"></slot>\ <ul>\ <slot name="second"></slot>\ </ul>\ </div>' }); //two 组件 Vue.component("two",{ props: ['name'], template: '<div>{{name}}</div>' }) //three 组件 Vue.component("three",{ props: ['age'], template: '<li>{{age}}</li>' }) var vm = new Vue({ el:"#app", data:{ username: "zhangsan", allages: [18,19,20] } }); </script> </body> </html>