🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] >[success] # 作用域插槽 **需求** : **组件内循环 div 标签,这个标签有可能不仅限于 div ,想通过父组件来决定循环的是什么标签** 。 **解决办法** :只需要在 **子组件slot标签** 上 **定义属性** 传给 **父组件** , **父组件** 只需要在 **调用子组件的标签** 上写 **v-slot="slotProps"** 来 **接收数据** ,在 **插槽内容** 中 **slotProps.xxx** ,就可以取到传递过来的数据了。 **作用域插槽应用场景** : **当子组件的渲染内容,要由父组件决定的时候** 。 **index.html** ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>使用插槽和具名插槽解决组件内容传递问题</title> <!-- 通过cdn方式引入vue --> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="root"></div> </body> <script> // 父组件 const app = Vue.createApp({ template: ` <list v-slot="slotProps"> <div> {{ slotProps.item }} </div> </list> ` }) // 子组件 app.component('list', { data(){ return { list: [1, 2, 3] } }, template: ` <div> <slot v-for="item in list" :item="item" /> </div> ` }) const vm = app.mount('#root') </script> </html> ~~~ 上面的 **v-slot="slotProps"** 是一个 **对象** 实际上这里有 **简写形式** ,可以写成对象的 **对象解构赋值** ,如下: ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>使用插槽和具名插槽解决组件内容传递问题</title> <!-- 通过cdn方式引入vue --> <script src="https://unpkg.com/vue@next"></script> </head> <body> <div id="root"></div> </body> <script> // 父组件 const app = Vue.createApp({ template: ` <list v-slot="{ item }"> <div> {{ item }} </div> </list> ` }) // 子组件 app.component('list', { data(){ return { list: [1, 2, 3] } }, template: ` <div> <slot v-for="item in list" :item="item" /> </div> ` }) const vm = app.mount('#root') </script> </html> ~~~