一、前言
這篇文章涉及的主要內容有:
1、ref綁定在標簽上是獲取DOM對象
2、ref綁定在子組件上獲取的是子組件對象
3、案列:自動獲取input焦點
二、主要內容
1、基礎內容:
ref
被用來給元素或子組件注冊引用信息。引用信息將會注冊在父組件的 $refs
對象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子組件上,引用就指向組件實例
(1)將ref綁定到標簽上:測試之后發現在mounted()函數之后拿到的是button對象
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id='app'></div> <script type="text/javascript" src="node_modules/vue/dist/vue.js"></script> <script> var App = { template:` <div class='app'> <button ref='btn'>我是按鈕1</button> </div>`, created(){ console.log(this.$refs.btn) }, beforeMount:function(){ console.log(this.$refs.btn); }, mounted(){ console.log(this.$refs.btn)//在這里才能拿到$refs.xxx } } new Vue({ el:'#app', data(){ return { } }, template:'<App />', components:{ App } }) </script> </body> </html>
(2)將ref綁定到子組件上:拿到的是子組件對象
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id='app'></div> <script type="text/javascript" src="node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> Vue.component('subCom',{ data(){ return{ } }, template:`<div> 這是子組件 </div>` }); var App = { data(){ return{ } }, template:`<div> <button ref='btn'>我是按鈕1</button> <button ref='btn2'>我是按鈕2</button> <subCom ref='a'></subCom> </div>`,//這里拿到的是子組件對象 created(){ console.log(this.$refs.btn); }, beforeMount(){ console.log(this.$refs.btn); }, mounted(){ console.log(this.$refs.btn); console.log(this.$refs.btn2); console.log(this.$refs.a); } } new Vue({ el:'#app', data(){ return{} }, template:'<App/>', components:{ App } }) </script> </body> </html>
2、自動獲取焦點
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id='app'></div> <script type="text/javascript" src="node_modules/vue/dist/vue.js"></script> <script type="text/javascript"> var App = { data: function (){ return { isShow:false } }, template:`<div class='app'> <input type='text' v-show='isShow' ref = 'input'/> </div>`, //$nextTick 是在DOM更新循環結束之后執行延遲回調,在修改數據后使用$nextTick可以獲取更新之后的DOM mounted:function(){ this.isShow = true; console.log(this.$refs.input); this.$nextTick(function() { this.$refs.input.focus(); }) } } new Vue({ el:'#app', data:function(){ return { } }, template:'<App/>', components:{ App } }); </script> </body> </html>
三、總結
1、ref不能重名,重名后面會覆蓋掉前面的
2、ref綁定到標簽上,$refs.xxx獲取到的是Dom對象
3、ref綁定到子組件上,獲取到的是子組件實例對象
4、$nextTick([callback])是下一次dom對象更新后執行里面的回調函數