前言:在JavaScript中需要通过document.querySelector('#demo')来获取dom节点,然后,再获取这个节点的值。在vue中,我们不用获取dom节点,元素绑定ref之后,直接通过this.$refs即可调用,这样可以减少获取dom节点的消耗。
一、介绍
ref有三种用法:
①ref加在普通的元素上,用this.ref.name获取到的是dom元素;
②ref加在子组件上,用this.ref.name获取到的是组件实例,可以使用组件的所有方法;
③如何利用v-for和ref获取一组数据或者dom节点。
当v-for用于元素或者组件的时候,引用信息将是包含dom节点或组件实例的数组;
关于ref注册时间的重要说明:因为ref本身是作为渲染结果被创建的,在初始渲染的时候,你不能访问它们--它们还不存在!$refs也不是响应式的,因此你不应该试图用它在模板中做数据绑定。
二、具体运用
ref介绍
ref被用来给元素或子组件注册引用信息,引用信息将会注册在父组件的$refs对象上。如果在普通的DOM元素上使用,那么指向的就是普通的DOM元素;如果用在子组件上,引用就指向该子组件的实例。
通俗的讲,ref特性就是为元素或子组件赋予一个ID引用,通过this.$ref.refName来访问元素或子组件的实例。
(1)基本用法,获取dom元素
<p ref="p">Hello</p>
<children ref="children"></children>
this.$refs.p
this.$refs.children
(2)获取子组件中的data和调用子组件中的方法
子组件code:
<template>
<div>{{msg}}</div>
</template>
<script>
export default {
data() {
return {
msg: "我是子组件"
}
},
methods: {
changeMsg() {
this.msg = "变身"
}
}
}
</script>
父组件code:
<template>
<div @click="parentMethod">
<children ref="children"></children>
</div>
</template>
<script>
import children from "components/children.vue"
export default {
components: {
children
},
data() {
return {}
},
methods: {
parentMethod() {
this.$refs.children //返回一个对象
this.$refs.children.changeMsg(); //调用children的changeMsg方法
}
}
}
</script>
附:子组件调用父组件的方法
子组件code:
<template>
<div>
</div>
</template>
<script>
export default {
methods: {
open() {
console.log("调用了");
// 调用父组件方法
this.$emit("refreshData");
}
}
}
</script>
父组件code:
<template>
<div id="app">
<HelloWorld ref="hello" @refreshData="getData"/>
<button @click="getHello">获取helloworld组件中的值</button>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
export default {
components: {
HelloWorld
},
data() {
return {}
},
methods: {
getHello() {
this.$refs.hello.open()
},
getData() {
console.log('111111')
}
}
};
</script>
this.$refs介绍
this.$refs是一个对象,持有当前组件中注册过ref特性的所有DOM元素和子组件实例。
注意:$refs只有在组件渲染完成后才填充,在初始渲染的时候,不能访问它们,并且它是非响应式的,因此不能用它在模板中做数据绑定。
当ref和v-for一起使用的时候,你得到的ref将会是一个包含了对应的数据源的这些子组件的数组。
<template>
<ul>
<li v-for="item in people" ref="refContent">{{item}}</li>
</ul>
</template>
<script>
export default {
data: {
return {
people:['one','two','three','four','five']
}
},
created(){
this.$nextTick(() => {
console.log(this.$refs.refContent);
})
},
mounted() {
console.log(this.$refs.refContent);
},
}
</script>
注意:
1.ref需要在dom渲染完成后才会有,在使用的时候确保dom已经渲染完成。比如:在生命周期mounted(){}钩子中调用,或者在this.$nextTick(()=>{})中调用;
2.如果ref是循环出来的,有多个重名,那么ref的值会是一个数组,此时,要拿到单个的ref只需要循环就可以了。
参考博客:Vue中ref和$refs的介绍以及使用方法示例 https://www.yht7.com/news/129698
vue里ref($refs)用法 https://www.cnblogs.com/goloving/p/9404099.html
vue中的ref和$refs https://segmentfault.com/a/1190000017098817
vue中的ref和$refs https://www.cnblogs.com/xumqfaith/p/7743387.html
vue中ref的作用 https://www.jianshu.com/p/623c8b009a85