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è)新特性):

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

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

  1. export default {
  2. data() {
  3. return {
  4. itemRefs: []
  5. }
  6. },
  7. methods: {
  8. setItemRef(el) {
  9. this.itemRefs.push(el)
  10. }
  11. },
  12. beforeUpdate() {
  13. this.itemRefs = []
  14. },
  15. updated() {
  16. console.log(this.itemRefs)
  17. }
  18. }

結(jié)合組合式 API:

  1. import { ref, onBeforeUpdate, onUpdated } from 'vue'
  2. export default {
  3. setup() {
  4. let itemRefs = []
  5. const setItemRef = el => {
  6. itemRefs.push(el)
  7. }
  8. onBeforeUpdate(() => {
  9. itemRefs = []
  10. })
  11. onUpdated(() => {
  12. console.log(itemRefs)
  13. })
  14. return {
  15. itemRefs,
  16. setItemRef
  17. }
  18. }
  19. }

注意:

  • 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)