在 vue 中渲染组件上的 this.$refs.xx 或 this.$el 上未定义

msq*_*qar 2 javascript vue.js

我不明白发生了什么,它应该很简单,但由于某种原因,我得到了undefined一个属性,当我调试它时,我可以看到它在那里,不是未定义的。组件已安装,该功能正在安装中使用,并且一切都应该在那里并且可以工作。但 Vue 一直说它是undefined.

这是模板:

<template>
    <div class="AnimatedCounter">
        <span ref="counterText" class="AnimatedCounter-text">{{ count }}</span>
    </div>
</template>
Run Code Online (Sandbox Code Playgroud)
mounted() {
    this.setCount(this.counter);
},
methods: {
    setCount: (val) => {
        /* $refs props and $el is "undefined" at runtime */
        const obj = this.$refs.counterText;

        anime({
            targets: this.$el,
            n: val,
            round: 1,
            duration: 500,
            easing: "linear",
            update: () => {
                this.count = obj.n;
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

无论我做什么,都会继续做同样的事情。我缺少什么?

Seb*_*lor 5

问题出在您编写函数的方式上。

您使用了箭头函数,它不会将this关键字绑定到 Vue 组件。它很可能引用了Window

您需要使用function关键字来声明您的函数,如下所示:

mounted() {
    this.setCount(this.counter);
},
methods: {
    setCount: function (val) {
        const obj = this.$refs.counterText;

        anime({
            targets: this.$el,
            n: val,
            round: 1,
            duration: 500,
            easing: "linear",
            update: () => {
                this.count = obj.n;
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)