ref的使用
获取HTML的dom元素
① 添加ref属性<h1 ref="zs1">App 根组件 {{books.length}}</h1>
②从vue对象中获取 this.$refs.zs1
<h1 ref="zs1">App 根组件 {{books.length}}</h1>
<button @click="changeColor">点击变红</button>
changeColor(){
console.log(this);
this.$refs.zs1.style.color = 'red'
},
获取组件的引用
案例需求
点击父组件中的按钮,操作子组件中的数据或方法
案例分析
需要获取到子组件的this对象,即子组件的vue对象
<Left ref="refLeft"></Left>
<button @click="change">点击操作子组件</button>
change(){
//子组件的this对象
console.log(this.$refs.refLeft)
this.$refs.refLeft.count = 0
this.$refs.refLeft.reSet()
}
this.$nextTick(cb) 方法
组件的 $nextTick(cb) 方法,会吧cb 回调推迟到下一个 dom 更新周期之后执行
案例需求:input 输入框 和 按钮 按需展示,input输入框自动获取焦点
<input type="text" v-if="inputVisible" @blur="showButton" ref="iptRef">
<button v-else @click="showInput">输入</button>
data(){
return{
inputVisible:false,
methods: {
showInput(){
this.inputVisible = true
this.$nextTick(()=>{
this.$refs.iptRef.focus()
})
},
showButton(){
this.inputVisible = false
},
changeColor(){
console.log(this);
this.$refs.zs1.style.color = 'red'
},