1.利用ref獲取dom對象
1.給標籤綁定
ref="xxx"
屬性,可以用this.$refs.xxx
獲取到原生dom對象
2.如果給組件綁定ref="xxx"
屬性,this.$refs.xxx
獲取到的是當前的組件對象
3.ref屬性值不能重名,否則後面會覆蓋前面的
<div id="app"></div>
<script>
var App = {
data(){
return {
}
},
template:`
<div class="app">
<button ref="btn">按鈕</button>
</div>
`,
created : function(){
console.log(this.$refs.btn);//undefined
},
beforeMount : function() {
console.log(this.$refs.btn);//undefined
},
mounted : function(){
console.log(this.$refs.btn);//<button>按鈕</button>
}
}
new Vue({
el: '#app',
data: function(){
return {
}
},
components : {
App
},
template : `
<App />
`
})
</script>
2.$nextTick()方法
在修改數據之後使用該方法,在dom更新循環結束後執行回調函數,在回調函數中獲取到更新後的dom。
var App = {
data(){
return {
isShow : false
}
},
template:`
<div class="app">
<input type="text" v-show="isShow" ref="input"/>
</div>
`,
mounted : function(){
this.isShow = true;
//this.$refs.input.focus()這樣直接寫是沒效果的
this.$nextTick(()=>{
this.$refs.input.focus()
})
}
}