【问题标题】:Vue js send data between two components NO propsVue js 在两个组件之间发送数据没有道具
【发布时间】:2019-02-27 08:04:21
【问题描述】:

您好,我正在尝试找到一种方法,将一些布尔值从组件 A 发送到组件 B,而无需相互嵌套,无需道具,只需发送数据,单向绑定。

    export default {
       data: function {
       return {
       value1: false,
       value2:true
    }
 }
}

【问题讨论】:

  • 这些组件之间有什么关系吗?如果它们完全不相关(不共享同一个父级或嵌套),则可能很难做到!你熟悉 VueX 吗?
  • 你在项目中使用 Vuex 吗?

标签: vue.js vuejs2 vue-component vuex vue-router


【解决方案1】:

用 Vuex 引入全局状态可能是解决这个问题的最好方法。

无需在系统中引入新的东西,您就可以使用事件总线来处理它。像这样引入侧通道的东西确实会增加您的应用程序的复杂性,但有时是必要的。

然后在你的组件中像这样使用它们

// eventBus.js
import Vue from 'vue';
export const EventBus = new Vue();

// To setup your component to listen and update based on new value
import { EventBus } from './eventBus';
mounted() {
  EventBus.$on('newValue', (val) => this.something = val);
}

// To send out a new value 
EventBus.$emit('newValue', 5);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 2019-07-08
    • 2020-11-06
    • 2020-12-07
    • 2020-01-21
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多