综述
我这里新建了两个div,一个div的id是graphic1,一个div的id是graphic2,分别通过两个按钮控制。包含v-show指令的div,在页面初次渲染后已经存在,只是不显示。
包含v-if指令的div,在页面初次渲染后是不存在的。
失败案例
代码
handleChange(value) {
console.log(value)
switch (value) {
case 'v-show': {
this.showGraphic1 = !this.showGraphic1
this.initGraphic(this.graphic_one, document.getElementById('graphic1'))
}
break;
case 'v-if': {
this.showGraphic2 = !this.showGraphic2
this.initGraphic(this.graphic_two, document.getElementById('graphic2'))
}
break;
}
},
结果
成功案例
代码
主要是使用了this.$nextTick()Vue官网解释
handleChange(value) {
console.log(value)
switch (value) {
case 'v-show': {
this.showGraphic1 = !this.showGraphic1
this.initGraphic(this.graphic_one, document.getElementById('graphic1'))
}
break;
case 'v-if': {
this.showGraphic2 = !this.showGraphic2
if (this.showGraphic2){
this.$nextTick(() => {
this.initGraphic(this.graphic_two, document.getElementById('graphic2'))
})
}
}
break;
}
},