1. 程式人生 > 程式設計 >v-slot和slot、slot-scope之間相互替換例項

v-slot和slot、slot-scope之間相互替換例項

如果元件文件裡面用的是v-slot,而你用的是vue2.6之前的版本,則需要替換v-slot:所以有兩種替換方式,注意看兩塊v-slot有啥不同,你就知道你該怎麼用slot-scope和slot來替換文件中的v-slot了

v-slot使用方式1:

<template v-slot:operate="{ row }"><template>

則可替換為:

<template slot="operate" slot-scope="{ row }"></template>

v-slot使用方式2:

<template v-slot="{ row }"><template>

則可替換為:

<template slot-scope="row"></template>

先記錄後期再完善,趕專案去了

補充知識:V-for and slot-scoped報錯問題

此場景是為了用v-for動態渲染表格的slot

可能會這麼寫

<a-table>
 <span v-for="(item,index) in header" :key="index" :slot="item.dataIndex" slot-scope="text" >
  {{ text }}
 </span>
</a-table>

但是這樣子會報錯,因為v-for和slot-scope在同一級

Ambiguous combined usage of slot-scope and v-for on (v-for takes higher priority). Use a wrapper < template> for the scoped slot to make it clearer.

提示在外邊包一層< template>,於是你可能改成下面這樣,但是也會報錯

<a-table>
 <template v-for="(item,index) in header" :key="index">
 <span :slot="item.dataIndex" slot-scope="text" >
  {{ text }}
 </span>
 </template>
</a-table>
< template> cannot be keyed. Place the key on real elements instead.

提示< template>template不能寫key, 即使沒有這個錯,表格資料也不會渲染出來,因為這一層沒有slot,應該說slot應該是放最外面,同時把:key放裡面

改成如下

<a-table>
 <template v-for="(item,index) in header" :slot="item.dataIndex" slot-scope="text">
 <span :key="index">
  {{ text }}
 </span>
 </template>
</a-table>

以上解決問題

有個slot沒有渲染的問題

 <template v-for="(slotname,idx) in ['status','sub_account_status']" :slot="slotname" slot-scope="text" >
  <span :key="idx">
  <a-tag v-if="text === '正常'" color="blue">{{ text }}</a-tag>
  <a-tag v-else color="red">{{ text }}</a-tag>
  </span>
 </template>
 <!-- 包名稱、關聯賬號 -->
 <template v-for="(slotname,idx) in ['app_name','roles']" :slot="slotname" slot-scope="text" >
  <span :key="idx">
  <a-tooltip placement="top" >
  <template slot="title">
  <span v-for="(item,index) in text" :key="index">{{ item }}<br/></span>
  </template>
  <div class="tableHidden">
  <a-tag v-for="(item,index) in text" :key="index">{{ item }} </a-tag>
  </div>
  </a-tooltip>
  </span>
 </template>

好像是因為2個v-for="(slotname,idx)"裡的slotname名字一樣了,對的,就是取的臨時變數名,修改成不一樣的就好了,神奇

 <template v-for="(name,'sub_account_status']" :slot="name" slot-scope="text" >
  // 上面那個name
  <span :key="idx">
  。。。
  </span>
 </template>
 <!-- 包名稱、關聯賬號 -->
 <template v-for="(slotname,'roles']" :slot="slotname" slot-scope="text" >
  <span :key="idx">
  。。。
  </a-tooltip>
  </span>
 </template>

以上這篇v-slot和slot、slot-scope之間相互替換例項就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。