Vue.js 3 中 ref 可通过两种方式使用:1. template ref 2. JavaScript ref。对于 template ref,可使用 this.$refs 访问,对于 JavaScript ref,可使用 unref() 解引用。ref 可用于访问 DOM 元素、组件实例和监听 DOM 事件。但注意 ref 的值是不可变的,首次访问时为 null,需使用 unref() 函数解引用 JavaScript ref 以获取实际 DOM 元素或组件实例。

ref 是 Vue.js 中一项强大的工具,可用于获取组件或 HTML 元素的引用。在 Vue.js 3 中,ref 的用法与之前版本略有不同。
在 Vue.js 3 中,ref 可通过两种方式使用:
1. template ref
<code class="html"><template> <input ref="myInput" /> </template></code>
2. JavaScript ref
立即学习“前端免费学习笔记(深入)”;
<code class="js">export default {
setup() {
const myInputRef = ref(null);
return { myInputRef };
},
};</code>对于 template ref,可以使用 this.$refs 访问:
<code class="js">const myInputElement = this.$refs.myInput;</code>
对于 JavaScript ref,可以使用 unref() 函数解引用:
<code class="js">const myInputElement = unref(myInputRef);</code>
ref 可用于各种场景:
1. 访问 DOM 元素
<code class="js">const myInputElement = this.$refs.myInput; myInputElement.focus();</code>
2. 访问组件实例
<code class="js">const myChildComponent = this.$refs.myChildComponent; myChildComponent.doSomething();</code>
3. 监听 DOM 事件
<code class="js">const myInputRef = ref(null);
watch(myInputRef, (newValue, oldValue) => {
if (newValue.value !== '') {
// do something
}
});</code>null,直到组件被渲染后才有效。unref() 函数解引用 JavaScript ref,以获取实际 DOM 元素或组件实例。以上就是vue3怎么用ref的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号