标签:loading res name 作用域 插槽 error data
定义一个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返回作用域插槽对象
标签:loading,res,name,作用域,插槽,error,data 来源: https://www.cnblogs.com/dangdanghepingping/p/15055037.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。