【问题标题】:Property or method ... is not defined on the instance but referenced during render属性或方法...未在实例上定义,但在渲染期间引用
【发布时间】:2020-09-02 07:39:54
【问题描述】:

我正在编写一个与事件一起使用的示例 Vue 组件。

我通过渲染 index.html 得到此错误:“属性或方法“onCouponApplied”未在实例上定义,但在控制台中的渲染期间被引用”。

index.html

<div id="root">
    <coupon @applied="onCouponApplied"></coupon>
</div>

以下是 Vue 代码

main.js

window.Event = new Vue();

Vue.component('coupon',{
    template: `<input placeholder="Enter" @blur="onCouponApplied">`,
    methods:{
        onCouponApplied() {Event.$emit('applied');}
    }
})

new Vue({
    el:"#root",
    created() {
        Event.$on('applied', ()=>alert('Received'));
    },
});

【问题讨论】:

  • 你在根组件上调用onCouponApplied,而不是coupon组件,同时你在优惠券组件上声明onCouponApplied方法,这就是为什么onCouponApplied没有定义
  • 为什么使用Event.$emit('applied');而不是this.$emit('applied');
  • @palaѕн 因为我想稍后用一个类替换 Event。它有什么问题?

标签: vue.js


【解决方案1】:

首先,Vue模板代码不属于index.html:&lt;div id="root"&gt;&lt;/div&gt;

然后,您将事件总线和普通的自定义 Vue 事件混为一谈。 要么:

window.Event = new Vue();

Vue.component("coupon", {
  template: `<input placeholder="Enter" @blur="onCouponApplied">`,
  methods: {
    onCouponApplied() {
      Event.$emit("applied");
    }
  }
});

new Vue({
  el: "#app",
  template: `<coupon></coupon>`,
  created() {
    Event.$on("applied", () => alert("Received"));
  },
});

或:

Vue.component("coupon", {
  template: `<input placeholder="Enter" @blur="$emit('applied')">`,
});

new Vue({
  el: "#app",
  template: `<coupon @applied="onCouponApplied"></coupon>`,
  methods: {
    onCouponApplied() {
      alert("Received");
    }
  }
});

【讨论】:

  • 为什么在新的 Vue 实例中使用 #app 作为元素?
  • 我想他只是用它来展示示例代码。你仍然可以使用#root,它仍然可以像这样正常工作。
  • 为什么没有在新的 Vue 实例中定义模板 &lt;coupon&gt; 就不能工作?
  • 是的,抱歉,将#app 替换为#root。您只在 index.html 中放置有效和静态的 html。 &lt;coupon&gt; 是一个 Vue 组件,需要在本地或全局导入 Coupon 组件的 Vue 组件或实例中使用。此外,@applied="onCouponApplied" 在纯 HTML 中没有任何意义。
  • @Renaud 我用v-on:applied="onCouponApplied" 对其进行了检查,并在Vue 实例中省略了template。错误仍然存​​在于控制台中,但它运行正常。这很奇特。
猜你喜欢
  • 2017-06-16
  • 2018-06-22
  • 2018-09-17
  • 2020-09-02
  • 2020-09-05
  • 2022-01-24
  • 2019-08-08
  • 2019-02-28
  • 2018-07-13
相关资源
最近更新 更多