天天看點

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]