首页 > 解决方案 > 在 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)
}

标签: javascripthtmlcssvue.js

解决方案


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>

推荐阅读