Javascript 为什么我的手表方法在Vue中不起作用

Javascript 为什么我的手表方法在Vue中不起作用,javascript,vue.js,vue-component,Javascript,Vue.js,Vue Component,我在一个js文件中有两个组件,文件以const EventBus=new Vue开头 我想将两个字符串“username”和“password”从第一个组件发送到第二个组件,但我不能这样做。我错在哪里 第一: Vue.component('log-reg-modal', { data: () => ({ username: "", password: "", }), watch: { username: functio

我在一个js文件中有两个组件,文件以const EventBus=new Vue开头

我想将两个字符串“username”和“password”从第一个组件发送到第二个组件,但我不能这样做。我错在哪里

第一:

Vue.component('log-reg-modal', {
    data: () => ({
        username: "",
        password: "",
    }),
    watch: {
        username: function(){
            EventBus.$emit('changed_username', this.username);
        },
        password: function(){
            EventBus.$emit('changed_password', this.password);
        },
    }

});
第二:

new Vue({
    el: '#app',
    vuetify: new Vuetify(),
    data: () => ({
        username: "",
        password: "",
    }),
    methods: {
        register : function (event) {
            EventBus.$on('changed_username', this.username);
            EventBus.$on('changed_password', this.password);
        }
    }
});
EventBus.on中指示的处理程序应该是函数,而不是道具本身。 在开始使用log reg modal组件之前是否调用了register方法? 您需要在创建的生命周期方法中使用EventBus.$on来注册接收事件

您也可以跳过EventBus,只使用“内置”事件处理程序

使用事件总线:

const EventBus=新的Vue; 常量LogRegModal={ 模板:` `, 数据:=>{用户名:,密码:}, 观察:{ 用户名:函数{EventBus.$emit\u username,this.username}, 密码:函数{EventBus.$emitchanged_password,this.password}, } }; 新Vue{ el:应用程序, 组件:{LogRegModal}, 数据:=>{用户名:,密码:}, 创造{ EventBus.$onchanged_username,val=>this.username=val; EventBus.$onchanged_password,val=>this.password=val; } };

这些值是从EventBus接收的:

用户名:{{Username} 密码:{{Password}} EventBus.$on方法应根据Vue生命周期在中的函数中创建

created (){
        EventBus.$on('changed_username', (data) => {
            this.username = data;
          });
        EventBus.$on('changed_password', (data) => {
            this.password = data;
          });
}

你的意思是我应该像事件总线那样替换它。$on'changed_username',data=>{this.username=data;};?以及如何为log reg modal调用register方法?我刚刚更新了我的答案,以展示如何在没有EventBus的情况下实现这一点。。干杯