比如我有这么一个需求:v-if=’condition ‘组件中有一个input,每次显示组件的时候,input获得焦点;我这么写
this.condition = true;
this.$refs.input1.focus();
发现,this.$refs每次都是undefined;
问题原因:渲染组件需要时间,并且时间没有JS执行的快;所以获取不到
解决办法:第一种利用setTimeout
this.condition = true;
setTimeout(()=>{
this.$refs.input1.focus();
},0)
第二种:利用 this.$nextTick
this.condition = true;
this.$nextTick(()=>{
this.$refs.input1.focus();
})