如何详细解释Vue中ref属性的应用方法?

更新于
2026-09-26 22:47:51
4阅读来源:SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计477个文字,预计阅读时间需要2分钟。

如何详细解释Vue中ref属性的应用方法?

一、ref的基本使用:使用ref+获取DOM节点--p ref=phello/p--

二、ref的使用:vm.$refs.p将会是DOM节点

--p ref=phello/p--

三、vm.$refs.child将会是子组件实例

----

四、如果在普通DOM元素上使用,引用指向的将是“

--ref=phello/--

一、ref的基本使用

ref的使用

<!-- `vm.$refs.p`将会是DOM结点 --> <p ref="p">hello</p> <!-- `vm.$refs.child`将会是子组件实例 --> <child-component ref="child"></child-component>

如果在普通的 DOM 元素上使用,引用指向的就是DOM 元素如果用在子组件上,引用就指向组件实例

深入理解$refs

某组件的$refs含有该组件的所有ref,看下面的例子

<div id="app"> <p ref="p">hello</p> <child-component ref="child"></child-component> </div> <script> Vue.component('child-component', { template: '<h1>child-component </h1>' }) let vm = new Vue({ el: '#app' }) </script>

从上图中我们很容易发现
vm.$refs返回了一个对象,这个对象内有两个成员,包含了vm实例的所有ref
vm.$refs.p是DOM 元素
vm.$refs.child是组件实例

二、实战:通过ref获取子组件data

看下面的例子

<div id="app"> <counter ref="child1" @change="handleChange"></counter> <counter ref="child2" @change="handleChange"></counter> <div>{{sum}}</div> </div> <script> // counter组件,实现每点击一次,自增1 Vue.component('counter', { template: '<h3 @click="handleClick">{{count}}</h3>', data() { return { count: 0 } }, methods: { handleClick() { this.count += 1; this.$emit('change') } } }) let vm = new Vue({ el: '#app', data: { sum: 0 }, methods: { handleChange() { this.sum = this.$refs.child1.count + this.$refs.child2.count // 使用refs获取子组件的数据 } } }) </script>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

如何详细解释Vue中ref属性的应用方法?

本文共计477个文字,预计阅读时间需要2分钟。

如何详细解释Vue中ref属性的应用方法?

一、ref的基本使用:使用ref+获取DOM节点--p ref=phello/p--

二、ref的使用:vm.$refs.p将会是DOM节点

--p ref=phello/p--

三、vm.$refs.child将会是子组件实例

----

四、如果在普通DOM元素上使用,引用指向的将是“

--ref=phello/--

一、ref的基本使用

ref的使用

<!-- `vm.$refs.p`将会是DOM结点 --> <p ref="p">hello</p> <!-- `vm.$refs.child`将会是子组件实例 --> <child-component ref="child"></child-component>

如果在普通的 DOM 元素上使用,引用指向的就是DOM 元素如果用在子组件上,引用就指向组件实例

深入理解$refs

某组件的$refs含有该组件的所有ref,看下面的例子

<div id="app"> <p ref="p">hello</p> <child-component ref="child"></child-component> </div> <script> Vue.component('child-component', { template: '<h1>child-component </h1>' }) let vm = new Vue({ el: '#app' }) </script>

从上图中我们很容易发现
vm.$refs返回了一个对象,这个对象内有两个成员,包含了vm实例的所有ref
vm.$refs.p是DOM 元素
vm.$refs.child是组件实例

二、实战:通过ref获取子组件data

看下面的例子

<div id="app"> <counter ref="child1" @change="handleChange"></counter> <counter ref="child2" @change="handleChange"></counter> <div>{{sum}}</div> </div> <script> // counter组件,实现每点击一次,自增1 Vue.component('counter', { template: '<h3 @click="handleClick">{{count}}</h3>', data() { return { count: 0 } }, methods: { handleClick() { this.count += 1; this.$emit('change') } } }) let vm = new Vue({ el: '#app', data: { sum: 0 }, methods: { handleChange() { this.sum = this.$refs.child1.count + this.$refs.child2.count // 使用refs获取子组件的数据 } } }) </script>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

如何详细解释Vue中ref属性的应用方法?