【发布时间】: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