ref的官网介绍
https://cn.vuejs.org/v2/api/#ref
需求
在普通的js
操作中,一般都是直接操作dom
元素,但是对于Vue.js
框架来说,一般是不允许直接操作dom
元素的。
那么其实Vue.js
框架提供了ref
获取dom元素,以及组件引用。
上面这两句话可能不能很清晰说明问题,直接上两个对比的代码,如下:
- 使用
js
直接获取dom
元素的文本内容
<h3 id="test_h3">dom元素中的内容h3>
document.getElementById('test_h3').innerText
- 使用
ref
获取dom
元素的文本内容
<h3 ref="test_h3">dom元素中的内容h3>
this.$refs.test_h3.innerText
示例:ref 获取 dom元素
span style="line-height: 26px;">html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="lib/vue.js">script>
head>
<body>
<div id="app1">
<h3 id="test_h3" @click="show" >dom元素中的内容h3>
<h3 @click="show2" ref="test_h3">dom元素中的内容h3>
div>
<script> // 创建第一个Vue的实例var vm1 = new Vue({el: '#app1',data: {},methods:{
show(){console.log('js获取h3的内容文本: ' + document.getElementById('test_h3').innerText);
},
show2(){console.log('ref获取h3的内容文本: ' + this.$refs.test_h3.innerText);
}
},
})script>
body>
html>
浏览器执行如下:
- 点击第一个h3,使用js获取dom元素,打印innerText文本内容
- 点击第二个h3,使用ref获取dom元素,打印innerText文本内容
从上面这里示例看出,ref
虽然跟js
都达到了获取dom
元素的目的,好像没有什么出彩的地方,就好像换了一个方式而已。
下面ref
还有一个更加重要的特性,就是可以引用组件中的data
、methods
等等。
示例:引用组件的data、methods
1.设置组件的ref属性
2.使用ref调用组件的data以及methods
3.浏览器执行显示
4.完整代码
span style="line-height: 26px;">html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="lib/vue.js">script>
head>
<body>
<div id="app1">
<input type="button" value="触发ref" @click="click_ref">
<com1 ref="com1">com1>
div>
<template id="com1">
<div>
<h1>com1私有组件的内容h1>
div>
template>
<script> // 创建私有组件com1var com1 = {template: "#com1",
data(){return {msg: "com1组件"
}
},methods: {
myclick(data1,data2){console.log("触发com1组件的myclick方法,msg = " + this.msg + ", data1 = " + data1 + ", data2 =" + data2);
}
}
}// 创建第一个Vue的实例var vm1 = new Vue({el: '#app1',data: {data1: "123",data2: "456",
},methods:{
click_ref(){// 使用ref引用组件的dataconsole.log("com1组件data中的msg = " + this.$refs.com1.msg);// 使用ref引用组件的methodsthis.$refs.com1.myclick(this.data1, this.data2);
}
},// 注册私有组件components:{
com1,
}
})script>
body>
html>
交流QQ群:
点击下面,查看更多Vue系列文章