简体   繁体   English

在 Vue.js 中不相关的组件之间共享数据

[英]Share data between unrelated components in Vue.js

This is the scenarios.这是场景。 I have a Graph component that appears in the body of the page, where the user can make some changes.我有一个显示在页面正文中的Graph组件,用户可以在其中进行一些更改。

I also have a Search component that appears in the header of the page.我还有一个出现在页面标题中的Search组件。

The two are unrelated - Graph only appears in the body of this one page, while Search appears in the header of all pages.两者无关Graph只出现在这一页的正文中,而Search出现在所有页面的页眉中。 They belong to app.js , which is currently just this:它们属于app.js ,目前只是这样:

require('./bootstrap');

window.Vue = require('vue');

Vue.component('search', require('./components/Search').default);
Vue.component('graph', require('./components/Graph').default);
/* other components */

import PerfectScrollbar from 'vue2-perfect-scrollbar'
import 'vue2-perfect-scrollbar/dist/vue2-perfect-scrollbar.css'

Vue.use(PerfectScrollbar);

const app = new Vue({
    el: '#app',

    data : {



    },

    methods : {



    },

    mounted : function(){



    },

    computed : {



    }
});

Now, when the user changes the data in Graph , I am supposed to send that change to Search .现在,当用户更改Graph的数据时,我应该将该更改发送到Search It doesn't really matter what the data is, I just need to figure out the sending process.数据是什么并不重要,我只需要弄清楚发送过程。

So, how do I send something from Graph to Search ?那么,如何将某些内容从Graph发送到Search I've been trying to emit the change, but I have no idea how to capture it in Search .我一直在尝试发出更改,但我不知道如何在Search捕获它。 I've used emit before with child/parent components, but I can't find documentation on how to do it here.我之前在子/父组件中使用过发射,但我找不到关于如何在此处执行此操作的文档。

Logically, I think it should go through app.js somehow, but I can't find the appropriate syntax.从逻辑上讲,我认为它应该以某种方式通过app.js ,但我找不到合适的语法。

In these cases you generally have two options.在这些情况下,您通常有两种选择。

The preferred method is to use Vuex , which gives your application a global state, which can be shared across your entire application.首选方法是使用Vuex ,它为您的应用程序提供全局状态,可以在整个应用程序中共享。 Making it easy to share data between components that have no direct relation.使在没有直接关系的组件之间共享数据变得容易。

The other option is to use an Event Bus, which gives you a way to listen and send events across your component.另一种选择是使用事件总线,它为您提供了一种跨组件侦听和发送事件的方法。 But this approach isn't considered best practice and should be avoided if possible.但这种方法不被视为最佳实践,应尽可能避免。

If you want do want to go with an event bus, Vue recommends using mitt .如果你想要想要去的事件总线,Vue公司建议使用手套

What you are looking for is called a centralized store or a State and Vuex is your answer.您正在寻找的称为centralized store或状态,而Vuex就是您的答案。

Vuex is a state management pattern + library for Vue.js applications. Vuex 是 Vue.js 应用程序的状态管理模式 + 库。 It serves as a centralized store for all the components in an application它充当应用程序中所有组件的集中存储

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM