javascript - 在 vue 中使用 ref 修改元素的样式会在切换路由中发送错误
问题描述
我使用 Vue 通过路由中的 ref 绑定 img 标签并让它定期旋转。但它显示Uncaught TypeError: Cannot read property 'style' of undefined
。我知道这是因为this.$refs.image
切换路由后变得未定义,但我不知道如何解决这个问题,以免出错。你能帮助我吗?
<img :src="this.picUrl" ref="image">
rotateMusicLogo() {
this.timer = setInterval(() => {
this.deg += 0.15;
if(this.deg >= 360) this.deg = 0;
this.$refs.image.style.transform = `rotate(${this.deg}deg)`;
}, 10)
}
解决方案
beforeDestroy
你应该在钩子上销毁你的计时器:
<script>
export default {
data () {
return {
timer: null
}
},
methods: {
rotateMusicLogo () {
this.timer = setInterval(() => {
this.deg += 0.15;
if(this.deg >= 360) this.deg = 0;
this.$refs.image.style.transform = `rotate(${this.deg}deg)`;
}, 10)
}
},
mounted () {
this.rotateMusicLogo()
},
beforeDestroy () {
clearInterval(this.timer)
}
}
</script>
推荐阅读
- vuejs2 - vue-i18n - 检测“未知”类型的令牌
- reactjs - 如何设置 aws-sdk 以从 s3 存储桶中的公共文件中获取文件内容?
- javascript - 动态加载图像,图像错误时中断循环
- wordpress - WP 重定向功能在实时站点上不起作用
- performance - Liferay 7 中搜索容器的性能不佳
- java - 如何修复“XSSFWorkbook 无法解析为类型”?
- c# - 如何以编程方式突出显示 DateTimePicker 中的特定部分?
- angular - 每次获取数据时,Angular rxjs-interval 运算符(轮询)都会重绘组件视图
- django - django xhtml2pdf表格边框问题
- html - CSS背景图像不显示在另一个之上