Vue使用v-for時動態綁定ref(v-for組件內使用ref)


前言

最近在開發中需要用到動態設置ref的內容,摸索了很久終於弄明白了要怎么實現。

1.綁定指定某一個組件

1.1、例如:這是一個編輯器組件,在這里把它的ref設置為myeditor
<fcEditor ref="myeditor"></fcEditor> 
1.2、在代碼中通過myeditor名稱獲取這個組件
this.$refs.myeditor; 

2.使用:ref動態設置組件名稱

2.1、例如:使用v-for循環展示一個對象數組,要遍歷的數組為steps
  data () { return { steps:[ {name:'itemName',title:"step1",id:1,content:"步驟一",orderNumber:1}, {name:'itemName',title:"step2",id:2,content:"步驟二",orderNumber:2}, {name:'itemName',title:"step3",id:3,content:"步驟三",orderNumber:3}] } } 
2.2、使用:ref動態設置ref,注意!這里所有的組件名稱都將被設置成itemName,你可能會說為什么不用item.id呢,是的,剛開始我也想用item.id,但是這樣雖然可以設置,但是在代碼中是無法取到的。
      <itemBox style="" class="itembox" v-for="item in steps" :key="item.id" :ref="item.name"> </itemBox> 
2.3、在代碼中獲取第一個組件
this.$refs.itemName[0]



原文:https://www.jianshu.com/p/8617f8852df7


免責聲明!

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



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