19 vue之ref属性
1 ref属性
ref放在普通标签上,拿到的就是普通标签本身(原生节点),原生节点的属性通过.获取
ref放在子组件上,拿到的就是子组件对象
-通过这种方式实现子传父(this.$refs.mychild.text)
-通过这种方式实现父传子(调用子组件方法传参数)
2 ref放在普通标签上
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>父子通信之子传父</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="box"> <input type="text" name="dzg" ref="myref"> <hr> <button @click="handleClick">点我试一试</button> </div> </body> <script> let vm = new Vue({ el: '#box', data: { }, methods:{ handleClick(){ console.log(this.$refs.myref) console.log(this.$refs.myref.value) console.log(this.$refs.myref.name) } } }) </script> </html>
3 ref放在子组件上
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ref放在子组件上</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="box"> <global ref="mychild"></global> <hr> <button @click="handleClick">点我试一试</button> </div> </body> <script> Vue.component('global', { template: ` <div> <h1>我是子组件</h1> </div> `, data() { return { show:false } }, methods: { handle1(msg) { console.log(msg) return 'dzg' } }, }) let vm = new Vue({ el: '#box', data: { }, methods:{ handleClick(){ // 拿到子组件对象 console.log(this.$refs.mychild) // 拿到子组件的属性 console.log(this.$refs.mychild.show) // 拿到子组件的方法 let res=this.$refs.mychild.handle1('666') console.log(res) } } }) </script> </html>
课堂案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>--> <script src="./js/vue.js"></script> </head> <body> <div class="app"> <h1>放在普通标签上</h1> <input type="text" v-model="myText" ref="myInput" name="xxx">===>{{myText}} <button @click="handleClick" ref="myButton">点我看美女</button> <hr> <h1>放在组件上</h1> <button @click="handleclick2">点我看帅哥</button> <child ref="mychild"></child> </div> </body> <script> Vue.component('child',{ template:` <div> <button>后退</button> {{name}} <button @click="handleC('前进')">前进</button> </div>`, data(){ return { name:'首页' } }, methods: { handleC(a){ alert(a) } }, }) var vm=new Vue({ el:'.app', data:{ myText:'yy' , }, methods:{ handleClick(){ console.log(this.$refs) console.log(this.$refs.myInput.value) console.log(this.$refs.myInput.name) }, handleclick2(){ console.log(this.$refs) console.log(this.$refs.mychild.name) this.$refs.mychild.name=this.myText this.$refs.mychild.handleC('前进个毛线') } } }) </script> </html>