Vue.js:属性或方法未在实例上定义,但它是

时间:2018-02-22 19:56:45

标签: vue.js

我有一个Vue.js组件,如下所示:

<!-- MyComponent.vue -->

<script>
  export default {
    render: () {
      return;
    },
    methods: {
      foo() {
        alert('hi');
      },
    },
  };
</script>

然后我的HTML看起来像这样:

<my-component @click="foo" />

当我运行时,我收到一个错误:

Property or method "foo" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

我似乎无法理解我在这里做错了什么 - 关于这个错误的所有其他SO问题似乎都是由范围问题引起的,但我只是处理一个简单的组件。

1 个答案:

答案 0 :(得分:2)

需要使用foo在组件中定义

my-component,而不是my-component本身。

此外,您需要@click.native,除非您在$emit中明确click名为my-component的事件。

如果您在html元素上使用此组件内的@click="foo",它将按预期工作(组件上的@click需要.native)。