1、ref 加在普通的元素上,用this.$refs.(ref值) 获取到的是dom元素
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title></head><body><div id="app"><p @click="handClick" ref="pp" id="p">你好web2208</p></div><script src="vue.js"></script><script type="text/javascript">const vm = new Vue({el:"#app",data(){return{ }},methods:{handClick(){console.log(document.getElementById("p"));console.log(this.$refs.pp);console.log(document.getElementById("p").innerHTML);console.log(this.$refs.pp.innerHTML);}}})</script></body>
</html>
2、ref 加在子组件上,用this.$refs.(ref值) 获取到的是组件实例,可以使用组件的所有方法。在使用方法的时候直接this.$refs.(ref值).方法() 就可以使用了。
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title><!-- ref 加在子组件上,用this.$refs.(ref值) 获取到的是组件实例,可以使用组件的所有方法。在使用方法的时候直接this.$refs.(ref值).方法() 就可以使用了。 --></head><body><div id="app"><counter ref="one" @change="handClick"></counter><counter ref="two" @change="handClick"></counter><h2>{{total}}</h2></div><script src="vue.js"></script><script type="text/javascript">Vue.component("counter", {template: `<div @click="handClick">{{number}}</div>`,data() {return {number: 0,}},methods: {handClick() {this.number++this.$emit("change")}}})const vm = new Vue({el: "#app",data() {return {total: 0}},methods: {handClick() {this.total = this.$refs.one.number + this.$refs.two.numberconsole.log(this.$refs); //这里的this.$refs指的是one、two两个组件实例}}})</script></body>
</html>
最后代码的效果就是x、y各点一次加1,最后实现x+y=z的效果
3、ref可以调用组件中的方法
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title></head><body><div id="app"><helloworld ref="hello"></helloworld><button @click="getHello">获取helloWorld组件中的值</button></div><script src="vue.js"></script><script type="text/javascript">Vue.component("helloworld",{template:`<div></div>`,data(){return{number:0}},methods:{handClick(){console.log("被调用了");}}})const vm = new Vue({el:"#app",data(){return{}},methods:{getHello(){this.$refs.hello.handClick() //调用了组件实例中的handClick方法console.log(this.$refs.hello); //调用了组件实例console.log(this.$refs.hello.number); //得到了组件实例中的number}}})</script></body>
</html>