借助 ref()
函數
用elementUI時,需要form表單驗證,文檔給的是 this.$refs[formName],但是在vue3中沒有this,
通過 ref
函數,依然可以實現類似 this.$refs
的功能。
首先在 setup
中定義一個 Ref
變量
import {ref, reactive ,onMounted} from "vue"; setup() { const divRef = ref(null) onMounted(() => { console.log(divRef.value) }) return { divRef } }
比如表單重置時,就可以使用
divRef .value.resetFields();
然后將這個 divRef
變量掛載到 DOM 上
<template> <div ref="divRef" /> </template>
這樣當 onMount
鈎子被觸發的時候,div 的 DOM 會在控制台打印出來。
另外 ref
也能實現動態關聯,具體實現可以參考文章 《$refs and the Vue 3 Composition API》