vue插槽的理解和使用及作用域插槽
阿新 • • 發佈:2020-12-13
什麼是插槽?
插槽就是子元件中的提供給父元件使用的一個佔位符,用<slot></slot> 表示,父元件可以在這個佔位符中填充任何模板程式碼,如 HTML、元件等,填充的內容會替換子元件的<slot></slot>標籤。
具名插槽:<slot name="fruit"></slot>
不具名插槽(預設插槽):<slot></slot>
有A元件和B元件,A元件中使用了B元件,則A元件是B元件的父元件。
A元件中需要使用到B元件的地方:<B></B>
B元件中定義模板,有部分待定的內容可插入slot插槽暫代,然後在A元件中定義。
概念大概是:
A元件:
<A>
<B>
我是填充到A元件插槽中的內容
</B>
</A>
B元件:
<B>
<h1>第一行</h1>
<slot>空著位置,等用到B元件的來填</slot>
<h1>第二行</h1>
</B>
總結:子元件(B)提供模板,中間可有插槽,父元件(A)使用模板元件(B),模板元件間的內容,作為填充到子元件插槽中的內容
作用域插槽
<!DOCTYPE html> <html lang="zh-en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>插槽作用域</title> <style> .current { color: orange; } </style> </head> <body> <div id="app"> <!-- 水果列表 --> <fruit :list="flist"> <!-- slot-scope是插槽slot傳遞來的屬性的集合 --> <template slot-scope="slotProps"> <strong v-if="slotProps.info.id==2" class="current"> {{slotProps.info.name}}{{slotProps}} </strong> <span v-else>{{slotProps.info.name}}</span> </template> </fruit> </div> <!-- 引入Vue --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> Vue.component('fruit', { // fruit元件的屬性 props: ['list'], template: ` <div> <ul> <li :key="item.id" v-for="item in list" > <slot :info="item"></slot> </li> </ul> </div> `, }) var app = new Vue({ el: '#app', data: { flist: [{ id: 1, name: 'apple', }, { id: 2, name: 'banana', }, { id: 3, name: 'orange', }], } }) </script> </body> </html>
執行結果:
slotProps是個物件,用來接收子元件傳遞來的引數