獲取DOM元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> <!-- <App></App> --> </div> <script type="text/javascript" src="../js/vue.min.js"></script> <script type="text/javascript"> var subComponent = { template: ` <div></div> ` }; Vue.component('subCom', subComponent); var App = { data: function() { return { } }, template: ` <div class='app'> <button ref = 'btn2'>我是另外一個按鈕</button> <button ref = 'btn'>我是按鈕1</button> <button ref = 'btn'>我是按鈕2</button> <subCom ref = 'subc'></subCom> </div> `, created: function() { console.log(this.$refs.btn); //返回的是undefined }, beforeMount: function() { console.log(this.$refs.btn); //返回的是undefined }, mounted: function() { // 如果是給標簽綁定ref屬性,使用this.$refs.xxx 獲取的是原生js的DOM對象 // ref 屬性值 不能重名 // 如果是給組件綁定的ref屬性 那么this.$refs.xxx獲取的是組件對象 console.log(this.$refs.btn); console.log(this.$refs.btn2); console.log(this.$refs.subc); } } new Vue({ el: '#app', data: function() { return { } }, template: `<App />`, components: { App } }); </script> </body> </html>
給DOM元素添加事件的特殊情況
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> </div> <script type="text/javascript" src="../js/vue.min.js"></script> <script type="text/javascript"> // 需求:input輸入框 獲取焦點 var App = { data: function() { return { isShow: false } }, template: ` <div class='app'> <input type="text" v-show = 'isShow' ref = 'input'/> </div> `, mounted: function() { this.isShow = true; console.log(this.$refs.input); // $nextTick 是在DOM更新循環結束之后執行延遲回調,在修改數據之后使用$nextTick 可以在回調中獲取到更新后的DOM this.$nextTick(function() { // 更新之后的DOM this.$refs.input.focus(); }) } } new Vue({ el: '#app', data: function() { return { } }, template: `<App />`, components: { App } }); </script> </body> </html>