我有一个项目,在项目中我有3个文件:
1。的index.html
2。 main.js
3。 Vue.js(Vue图书馆)
我的index.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
body{
padding-top: 40px;
}
</style>
</head>
<body>
<div id="root" class="container">
<coupon @applied="OnCouponApplied"></coupon>
<h1 v-show="couponApplied">applied</h1>
</div>
<script src="../index/vue.js"></script>
<script src="main.js"></script>
</body>
</html>
我的main.js:
window.Event=new Vue();
Vue.component('coupon',{
name:'coupon',
template:'<input placeholder="enter you`r code" @blur="OnCouponApplied">',
methods:{
OnCouponApplied(){
Event.$emit('applied');
}
}
});
new Vue({
el:'#root',
data:{
couponApplied:false
},
created(){
Event.$on('applied',()=>alert('handle!'));
}
});
但我有两个警告:
警告:
vue.js:597 [Vue warn]: Property or method "OnCouponApplied" 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. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
(found in <Root>)
vue.js:597 [Vue warn]: Invalid handler for event "applied": got undefined
found in
---> <Coupon>
<Root>
它的工作正确,现在我也想知道这个警告是否有任何解决方案!!?!?
答案 0 :(得分:2)
main.js
中,我们在Vue实例中没有OnCouponApplied
。
所以我删除了OnCouponApplied
中的index.html
。
并修复main.js
以获得更好的视图(不要使用$ emit和$ on):
window.Event=new class{
constructor(){
this.vue=new Vue();
}
fire(event,data=null){
this.vue.$emit(event,data);
}
listen(event,callback){
this.vue.$on(event,callback);
}
};
Vue.component('coupon',{
name:'coupon',
template:'<input placeholder="enter you`r code" @blur="OnCouponApplied">',
methods:{
OnCouponApplied(){
Event.fire('applied');
}
}
});
new Vue({
el:'#root',
created(){
Event.listen('applied',()=>alert('handle!'));
}
});