数据改变,更新视图是异步的
解决方法一:添加延时器
解决方法二:$nextTick(作用:等待视图更新完成)
示例:通过ref获取元素更新后的数据
<template>
<div>
<h1 ref="h1">{{count}}</h1>
<button @click="addFn">按钮</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0,
};
},
methods: {
addFn() {
console.log(this.count);//0
this.count++
console.log(this.count);//1
// 数据更新 视图还没更新 获取的数据是更新前的
console.log(this.$refs.h1.innerHTML);//0
// 解决方法一 设置延时器
setTimeout(() => {
console.log(this.$refs.h1.innerHTML);//1
},1000)
// 解决方法三 设置$this.$nextTick
this.$nextTick(()=>{
console.log(this.$refs.h1.innerHTML);//1
})
},
},
// 解决方法二 在更新钩子函数里面监听
updated(){
console.log(this.$refs.h1.innerHTML);//1
}
};
</script>
<style>
</style>
示例:通过ref让input框获取焦点
<template>
<div>
<button v-if="isShow" @click="tabFn">按钮</button>
<input ref="ipt" v-else type="text" />
</div>
</template>
<script>
export default {
data() {
return {
isShow: true,
};
},
methods:{
tabFn(){
this.isShow=false
// 方法一
// setTimeout(() => {
// this.$refs.ipt.focus()
// }, 500);
// 方法二
this.$nextTick(()=>{
this.$refs.ipt.focus()
})
}
}
};
</script>
<style>
</style>