【问题标题】:Warning in vue dev toolVue开发工具中的警告
【发布时间】:2018-11-10 14:35:06
【问题描述】:

我有一个项目,在项目中我有 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 警告]:属性或方法“OnCouponApplied”未在实例上定义,但在渲染期间被引用。通过初始化该属性,确保此属性是反应性的,无论是在数据选项中,还是对于基于类的组件。请参阅:https‍://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties。

(在 中找到)

vue.js:597 [Vue 警告]:事件“应用”的处理程序无效:未定义

发现于

--->

它工作正常,现在我也想知道这些警告有什么解决方案吗?

【问题讨论】:

  • 在正文中,&lt;coupon @applied="OnCouponApplied"&gt;&lt;/coupon&gt; 使用的是在根 Vue 实例中不存在的OnCouponApplied
  • 非常感谢您的帮助。

标签: javascript vue.js vuejs2 vue-component dom-events


【解决方案1】:

main.js 中,我们在 Vue 实例中没有 OnCouponApplied

所以我删除了index.html 中的OnCouponApplied

并修复 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!'));
    }
});

【讨论】:

  • 重新定义window.Event 不是一个好主意。我会选择一个不同的名字。
  • 如果您有其他想法,请在回答模式中为我发帖。谢谢。
  • 事实上,您可以将代码包装在 IIFE(至少)中,这样您就不需要全局变量了。
  • Vue.use(function (_Vue) { _Vue.prototype.$myBus = new class{ constructor(){ this.vue=new Vue(); } fire(event,data=null){ this.vue.$emit(event,data); } listen(event,callback){ this.vue.$on(event,callback); } } }, {})一样注册你的事件总线,像this.$myBus.fire('applied')一样使用它
猜你喜欢
  • 2020-10-31
  • 2011-04-27
  • 1970-01-01
  • 2021-09-30
  • 2018-07-14
  • 2019-11-11
  • 2020-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多