首页 > 解决方案 > 通过自定义 Vue 组件中的方法访问实例

问题描述

我正在尝试通过自定义注册的 Vue 组件中的触发方法访问实例方法/数据。

下面是一个基本示例:

Vue.component('example-component', {
        template: `<div>
                        <h2>Count: {{count}}</h2>
                        <button class="btn btn-primary" v-on:click="increment()">Increment</button>
                    </div>`,
        data: () => {
            return {
                count: 0
            }
        },
        methods: {
            increment: () => {
                console.log("Click!");
                console.log("Current count: ", this.count);
                this.count++;
                console.log("New count: ", this.count);
            },
            decrement: () => {
                // other function
            }
        },
        mounted: () => {
            console.log("Example component mounted!");
        }
    });

结果:

Example component mounted!
Click!
Current count:  undefined
New count:  NaN

您可能会注意到属性“count”已在组件挂载期间加载,并且在 HTML 中可用/呈现。方法“increment()”也已被触发。然而,'this.count' 似乎是无法访问的,就像其他可能的方法(例如'this.decrement()')会抛出 TypeError this.decrement is not a function。

如果这种方法是可能的,有什么建议吗?

PS。我知道通过 .vue 文件注册表的默认方法,例如:

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

标签: vue.jsvue-component

解决方案


来自官方文档的解释:

Vue 自动绑定方法的 this 值,以便它始终引用组件实例。这可确保方法在用作事件侦听器或回调时保留正确的 this 值。在定义方法时应该避免使用箭头函数,因为这会阻止 Vue 绑定适当的 this 值。

Phoenix 上面的答案似乎是有效的,我只能补充一点,您也可以用简短的形式编写函数,例如:

increment() { ... },
decrement() { ... }

在我看来,这看起来更好,虽然有细微的差别。


推荐阅读