Vue 3.0 v-for中的Ref數(shù)組

2021-07-16 11:44 更新

在 Vue 2 中,在 v-for 里使用的 ref attribute 會(huì)用 ref 數(shù)組填充相應(yīng)的 $refs property。當(dāng)存在嵌套的 v-for 時(shí),這種行為會(huì)變得不明確且效率低下。

在 Vue 3 中,這樣的用法將不再在 $ref 中自動(dòng)創(chuàng)建數(shù)組。要從單個(gè)綁定獲取多個(gè) ref,請(qǐng)將 ref 綁定到一個(gè)更靈活的函數(shù)上 (這是一個(gè)新特性):

<div v-for="item in list" :ref="setItemRef"></div>

結(jié)合選項(xiàng)式 API:

export default {
  data() {
    return {
      itemRefs: []
    }
  },
  methods: {
    setItemRef(el) {
      this.itemRefs.push(el)
    }
  },
  beforeUpdate() {
    this.itemRefs = []
  },
  updated() {
    console.log(this.itemRefs)
  }
}

結(jié)合組合式 API:

import { ref, onBeforeUpdate, onUpdated } from 'vue'


export default {
  setup() {
    let itemRefs = []
    const setItemRef = el => {
      itemRefs.push(el)
    }
    onBeforeUpdate(() => {
      itemRefs = []
    })
    onUpdated(() => {
      console.log(itemRefs)
    })
    return {
      itemRefs,
      setItemRef
    }
  }
}

注意:

  • itemRefs 不必是數(shù)組:它也可以是一個(gè)對(duì)象,其 ref 會(huì)通過迭代的 key 被設(shè)置。
  • 如果需要,itemRef 也可以是響應(yīng)式的且可以被監(jiān)聽。
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)