前言
最近在開發中需要用到動態設置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]