作用域插槽
定义一个myslot插槽的组件,用于显示请求数据的结果:请求中,请求数据或者请求错误;
1 <template> 2 <div class="slot-container"> 3 <slot name="loading" v-if="loading"></slot> 4 <slot name="error" v-bind:res="res" v-else-if="error"></slot> 5 <slot v-else v-bind:res="res"></slot> 6 </div> 7 </template> 8 9 <script> 10 export default { 11 props: ['getData'], 12 data() { 13 return { 14 loading: true, 15 error: false, 16 res: undefined, 17 }; 18 }, 19 20 async created() { 21 const data = await this.getData(); 22 this.loading = false; 23 24 if (data.msg == 'ok') { 25 this.error = false; 26 } else { 27 this.error = true; 28 } 29 this.res = data.data; 30 console.log(this.res); 31 }, 32 }; 33 </script>
应用该请求插槽组件
<template> <MySlot :getData="getData"> <template v-slot:loading> loading... </template> <template v-slot:error="slotProps"> {{slotProps.res}} </template>//v-slot:error里的error是指对应的slot的name;slotProps是指传来的值 <template v-slot='slotProps'>
<ul>
<li v-for='item in slotProps.res'>
{{item.name}} --- {{item.age}}
</li>
</ul>
</template> </MySlot> </template> import MySlot from './MySlot.vue'; export default { components: { MySlot, }, methods: { async getData() { return new Promise((res) => { setTimeout(() => { const random = Math.random(); if (random > 0.5) { const arr = [ { name: '张三', age: 10 }, { name: '李四', age: 10 }, { name: '王五', age: 10 }, ]; res({ msg: 'ok', code: 0, data: arr, }); } else { res({ msg: 'error', code: 1, data: 'a error request', }); } }, 1000); }); }, } }; </script>
原理:将插槽中的内容(ul>li)转换成一个函数,{default:function(){
return vnode;
}}
调用这个函数default(slotProps){
}
在插槽组件中的$slots和$scopedSlots
$slots: 返回普通插槽的对象
$$scopedSlots返回作用域插槽对象