阅读 291

Vue中ref和$refs的介绍以及使用方法示例

这篇文章主要给大家介绍了关于Vue中ref和$refs使用方法的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

在JavaScript中需要通过document.querySelector("#demo")来获取dom节点,然后再获取这个节点的值。在Vue中,我们不用获取dom节点,元素绑定ref之后,直接通过this.$refs即可调用,这样可以减少获取dom节点的消耗。

ref介绍

ref被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向该子组件实例

通俗的讲,ref特性就是为元素或子组件赋予一个ID引用,通过this.$refs.refName来访问元素或子组件的实例

12<p ref="p">Hello</p><children ref="children"></children>
12this.$refs.pthis.$refs.children

this.$refs介绍

this.$refs是一个对象,持有当前组件中注册过 ref特性的所有 DOM 元素和子组件实例

注意: $refs只有在组件渲染完成后才填充,在初始渲染的时候不能访问它们,并且它是非响应式的,因此不能用它在模板中做数据绑定

注意:

当ref和v-for一起使用时,获取到的引用将会是一个数组,包含循环数组源

1234567891011121314151617181920212223<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>

实例(通过ref特性调用子组件的方法)

【1】子组件code:

1234567891011121314151617181920<template> <div>{{msg}}</div></template>  <script>export default { data() { return {  msg: '我是子组件' } }, methods: { changeMsg() {  this.msg = '变身' } }}</script>  <style lang="sass" scoped></style>

【2】父组件code:

12345678910111213141516171819202122232425<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的介绍以及使用的文章就介绍到这了



文章分类
ANDROID
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐