發布於 2023-03-21

更新於 2023-03-21

程式

約267字 (2分鐘閱讀)

[Day 28] Vue3 處理 $refs undefined 的 3 種方法 - 嘗試 30 日寫文充版挑戰

Title Image

Photo by Emily Morter on Unsplash

前言 - Prologue

嘗試寫 30 天文充實版面 (跳過假日 ლ(́◕◞౪◟◕‵ლ) ) 更新文章的 Day 28

接續前兩篇文章,這次將會寫一下 Vue3 遇到 $refs 出現 undefined 時候要怎麼辦。簡短的抓重點介紹一下

正文 - Main text

解決 $refs undefined 問題的 3 種 Vue3 方法:

  1. 使用 ref 模板引用
  2. $nextTick 中取得 $refs
  3. onMounted 中使用 ref 函數
方法一:使用 ref 模板引用

使用 v-if 確認 $refs 是否存在。

例如:

<div v-if="$refs.foo">
  Hello World!
</div>
方法二:在 $nextTick 中取得 $refs

使用 $nextTick 確保 DOM 元素渲染完成後再取得 $refs

例如:

methods: {
  handleClick() {
    this.$nextTick(() => {
      console.log(this.$refs.foo);
    });
  }
}
方法三:在 onMounted 中使用 ref 函數

使用 setup() 中的 ref() 方法。

例如:

setup() {
  const fooRef = ref(null);
  onMounted(() => {
    console.log(fooRef.value);
  });
  return {
    fooRef
  };
}

後記 - Epilogue

因為前兩篇主要介紹部落格中 Vue2 時所遇到的問題比較詳細(?),這篇就不做詳細講解的部分拉。(繼續回去鑽研 React 技術)

[Day 28] Vue3 處理 $refs undefined 的 3 種方法 - 嘗試 30 日寫文充版挑戰

https:///blog/47

作者

Kama

Read more from 程式
lightbox-image
Toggle Button - Red Pandas Icons by svgrepo.com

Copyrights © 2023 Kama, All Rights Reserved.