我是靠谱客的博主 欣慰钻石,这篇文章主要介绍Vue中ref的用法及演示,现在分享给大家,希望可以做个参考。

ref 定义:被用来给元素或子组件注册引用信息。引用信息会被注册在父组件上的$refs对象上。

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

举例:

组件1:

 

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<template> <div> 我是{ {name}} </div> </template> <script> export default { name:'Cpn1', data() { return { name:'组件1' } }, } </script>

组件2:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template> <div>我是{ {name}}</div> </template> <script> export default { name:'Cpn2', data() { return { name:'组件2' } }, } </script>

App.vue

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<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中ref的用法及演示的文章就介绍到这了,更多相关Vue中ref的用法内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是欣慰钻石最近收集整理的关于Vue中ref的用法及演示的全部内容,更多相关Vue中ref内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(184)

评论列表共有 0 条评论

立即
投稿
返回
顶部