

这篇文章主要介绍了Vue中ref的用法及演示,ref被用来给元素或子组件注册引用信息。引用信息会被注册在父组件上的$refs对象上,下面来看看文章的详细内容,需要的朋友可以参考一下。
ref 定义:被用来给元素或子组件注册引用信息。引用信息会被注册在父组件上的$refs对象上。
- 如果是在普通的
dom元素上使用,引用指向的就是dom元素; - 如果用在子组件上,引用指向的就是组件实例。
举例:
组件1:
<template>
<div>我是{ {name}}</div>
</template>
<script>
export default {
name: "Cpn1",
data() {
return {
name: "组件1",
};
},
};
</script>
组件2:
<template>
<div>我是{ {name}}</div>
</template>
<script>
export default {
name: "Cpn2",
data() {
return {
name: "组件2",
};
},
};
</script>
App.vue
<template>
<div id="app">
<cpn-1 ref="c1"></cpn-1>
<cpn-2 ref="c2"></cpn-2>
<button @click="showDom">按钮</button>
<h2 ref="title">我是标题</h2>
<input type="text" ref="input" value="123" />
</div>
</template>
<script>
import Cpn1 from "./components/Cpn1.vue";
import Cpn2 from "./components/Cpn2.vue";
export default {
components: {
Cpn1,
Cpn2,
},
name: "App",
methods: {
showDom() {
console.log(this.$refs.c1);
console.log(this.$refs.c2.$data.name);
console.log(this.$refs.title);
console.log(this.$refs.input.value);
// 获取一个真实的dom对象并修改值
var title = this.$refs.title;
title.innerText = "helloWord";
},
},
};
</script>
执行上面的程序,点击页面上的《按钮》,效果如下:

同时看控制台:

可以看到当 ref 对象用在普通元素上时获取到的是普通DOM元素,当 ref 用在子组件上时,引用指向组件实例。
根据实际需要,可以通过 ref 给元素或者子组件注册引用信息,在需要用到的时候我们可以通过 $refs 获取真实的DOM元素或者组件实例进行我们想要的操作。
参考资料
Vue | Vue中 ref 的用法小结_儒雅的烤地瓜的优快云博客
Vue | vue中 $refs 的三种用法解读_儒雅的烤地瓜的优快云博客
Vue | vue中$refs的用法及作用详解_儒雅的烤地瓜的优快云博客
Vue中ref、reactive、toRef、toRefs、$refs的基本用法总结_vue.js_脚本之家


884

被折叠的 条评论
为什么被折叠?



