Vue插槽 v-slot 指令


2.6.0版本,v-slot 指令取代了 slot 和 solt-scope 指令

 

編譯作用域

父級模板里的所有內容都是在父級作用域中編譯的;子模板里的所有內容都是在子作用域中編譯的。

后備內容

有時為一個插槽設置具體的后備 (也就是默認的) 內容是很有用的,它只會在沒有提供內容的時候被渲染

具名插槽

v-slot: 取代 slot="" , 切只能用在 <template> 標簽內

1 <template v-slot:header></template>

作用域插槽

v-slot="" 取代 solt-scope=""

<template v-slot:default="slotProps">

 

 


 

作用域插槽 說明

有時讓插槽內容能夠訪問子組件中才有的數據是很有用的。例如,設想一個帶有如下模板的 <current-user> 組件:

<span>
  <slot>{{ user.lastName }}</slot>
</span>

我們可能想換掉備用內容,用名而非姓來顯示。如下:

<current-user> {{ user.firstName }} </current-user>

然而上述代碼不會正常工作,因為只有 <current-user> 組件可以訪問到 user 而我們提供的內容是在父級渲染的。

 

為了讓 user 在父級的插槽內容中可用,我們可以將 user 作為 <slot> 元素的一個 attribute 綁定上去:

<span>
  <slot v-bind:user="user"> {{ user.lastName }} </slot>
</span>

綁定在 <slot> 元素上的 attribute 被稱為插槽 prop。現在在父級作用域中,我們可以使用帶值的 v-slot 來定義我們提供的插槽 prop 的名字:

<current-user>
  <template v-slot:default="slotProps"> {{ slotProps.user.firstName }} </template>
</current-user>

在這個例子中,我們選擇將包含所有插槽 prop 的對象命名為 slotProps,但你也可以使用任意你喜歡的名字。

 

 


 

補充說明 : 

學習中的實例,當使用 Element 的 table-column 組件時,會碰到 row 的參數 ,如下:

//2.6之前
<template slot-scope="scope">
    {{scope.row}}
</template>

//2.6之后
<template v-slot"anypropname">
    {{anypropname.row}}
</template>

//可以使用ES6 解構
<template v-slot"{row:row}">  //這一行可以直接簡寫為 {row}
    {{row}}
</template>

這里的 row 是 Element 特有的參數 ,代表 slot 中傳入的一行的內容,參考如下

 

 

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM