vue ref的使用
1、给标签设置ref属性
<h2 ref='midautumn'>中秋快乐111</h2>
2、在mounted()中使用$refs对获取到的标签使用(methods与data等平级)
mounted(){ //打印出所有带ref属性的值,是一个对象,{midautumn: h2, mid-autumn: h3, son2: VueComponent} console.log(this.$refs); // 打印出名ref属性为midautumn的标签h2 console.log(this.$refs.midautumn);//h2 // ref属性为mid-autumn的标签h3 console.log(this.$refs['mid-autumn']); // 使用$refs将h2颜色改为red this.$refs.midautumn.style.color = 'red'; // js可以获取子组件渲染后的内容<div id='son2'>...</div> console.log(document.getElementById('son2')); // refs获取子组件son2 VueComponent {_uid: 1, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …} console.log(this.$refs.son2); // refs获取子组件中data数据msg console.log(this.$refs.son2.msg); // refs获取子组件中methods方法 console.log(this.$refs.son2.log1()); }
3、ref与js获取id的区别:
ref可以获取子组件中所有内容
id只能获取渲染后的标签
示例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id='app'> <h2 ref='midautumn'>中秋快乐111</h2> <h3 ref='mid-autumn'>中秋快乐222</h3> <son id="son2" ref='son2'></son> </div> <template id="son"> <div>放假还得写作业,一点不快乐<br> {{msg}} </div> </template> <script> const vm = new Vue({ el: '#app', data: { }, methods: { }, components:{ son:{ template:'#son', data(){ return{ msg:'我不是真正的快乐' } }, methods:{ log1(){ return 111 } } } }, mounted(){ //打印出所有带ref属性的值,是一个对象,{midautumn: h2, mid-autumn: h3, son2: VueComponent} console.log(this.$refs); // 打印出名ref属性为midautumn的标签h2 console.log(this.$refs.midautumn);//h2 // ref属性为mid-autumn的标签h3 console.log(this.$refs['mid-autumn']); // 使用$refs将h2颜色改为red this.$refs.midautumn.style.color = 'red'; // js可以获取子组件渲染后的内容<div id='son2'>...</div> console.log(document.getElementById('son2')); // refs获取子组件son2 VueComponent {_uid: 1, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …} console.log(this.$refs.son2); // refs获取子组件中data数据msg console.log(this.$refs.son2.msg); // refs获取子组件中methods方法 console.log(this.$refs.son2.log1()); } }) </script> </body> </html>
打印结果:
1、浏览器
2、console控制台