需求
界面渲染数学公式会存在bug,时间较长等情况下渲染公式出错,需要自动定时刷新页面公式,同时为了不占用过多资源,退出该界面要清除定时器。
实现
需要使用created()
和destroyed()
方法,在created方法中设置定时器,并给让定时器等于Data中设置的变量,在destroyed离开界面时调用的方法体内,根据这个变量清除指定定时器。(下文只包含主要代码)
<span :key="key" style="font-size:20px">{{ text }}</span>
//中间省略
data() {
return {
key: 0,
myVar: null,
text: ''
}
},
created() {
this.myVar = setInterval(() => {
this.key += 1
console.log('执行定时器')
}, 1000)
},
destroyed() {
clearInterval(this.myVar)
},
methods: {
}
上面的是刷新组件的方式(渲染公式好像有点bug),也可以用重新渲染公式的方式(box-card
为含有公式的组件的class):
created() {
this.timer = setInterval(() => {
// this.key += 1
console.log('执行定时器')
this.$nextTick(function() { // 这里要注意,使用$nextTick等组件数据渲染完之后再调用MathJax渲染方法,要不然会获取不到数据
if (this.commonsVariable.isMathjaxConfig) { // 判断是否初始配置,若无则配置。
this.commonsVariable.initMathjaxConfig()
}
this.commonsVariable.MathQueue('box-card')// 传入组件id,让组件被MathJax渲染
})
}, 1000)
},