这篇文章将为大家详细讲解有关如何在Vue中使用ref和$refs方法,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
ref被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向该子组件实例
通俗的讲,ref特性就是为元素或子组件赋予一个ID引用,通过this.$refs.refName来访问元素或子组件的实例
<p ref="p">Hello</p>
<children ref="children"></children>
this.$refs.p
this.$refs.children
this.$refs是一个对象,持有当前组件中注册过 ref特性的所有 DOM 元素和子组件实例
注意: $refs只有在组件渲染完成后才填充,在初始渲染的时候不能访问它们,并且它是非响应式的,因此不能用它在模板中做数据绑定
注意:
当ref和v-for一起使用时,获取到的引用将会是一个数组,包含循环数组源
<template>
<div>
<div ref="myDiv" v-for="(item, index) in arr" :key="index">{{item}}</div>
</div>
</template>
<script>
export default {
data() {
return {
arr: ['one', 'two', 'three', 'four']
}
},
mounted() {
console.log(this.$refs.myDiv)
},
methods: {}
}
</script>
<style lang="sass" scoped>
</style>
【1】子组件code:
<template>
<div>{{msg}}</div>
</template>
<script>
export default {
data() {
return {
msg: '我是子组件'
}
},
methods: {
changeMsg() {
this.msg = '变身'
}
}
}
</script>
<style lang="sass" scoped></style>
【2】父组件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>
<style lang="sass" scoped></style>
关于如何在Vue中使用ref和$refs方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。