前言 - Prologue
嘗試寫 30 天文充實版面 (跳過假日 ლ(́◕◞౪◟◕‵ლ) ) 更新文章的 Day 28
接續前兩篇文章,這次將會寫一下 Vue3 遇到 $refs
出現 undefined
時候要怎麼辦。簡短的抓重點介紹一下
正文 - Main text
解決 $refs undefined
問題的 3 種 Vue3 方法:
- 使用
ref
模板引用
- 在
$nextTick
中取得 $refs
- 在
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 技術)