讨论组件之间如何大规模共享数据,以及使用Vue / Vuex应用程序的示例代码。
![组件以及它们如何在Vue和Vuex中进行交互](http://p2.ttnews.xyz/loading.gif)
Vue作为一个渐进式框架,在语法方面与Angular相似。为了理解Vue中的组件以及Vuex的用途,首先,我们将介绍Vue如何提供在组件之间共享数据的能力。
什么是组件?为什么我们需要在组件之间共享数据?如果您熟悉Angular指令,那么它就像一个简单的指令,我们可以编写自己的逻辑,提供模板(模板),并调用该组件(而不是将组件注册到根实例)。
![组件以及它们如何在Vue和Vuex中进行交互](http://p2.ttnews.xyz/loading.gif)
示例:
//Button directive componentVue.component('button-directive', {data: function () {return {counterValue: 0}}template: '-Button Counter-'});
上面的例子显示了一个单独的组件,但是如果有多个组件与父组件和子组件共享相同的实例?使用各种技术在组件(子组件和父组件)之间共享。
例:
事件可以用类似的格式发起:
export default {methods: {fireEvent() {this.$emit('eventExample', eventValueOne);}}}道具和事件都可以与v-modal一起用于双向绑定,其中输入值的更改将调用该 triggerEvent 方法。
例:
2. 提供/注入这允许从祖先组件到其所有后代选择性地展示数据或方法。虽然提供/注入本身并不具有反应性,但它可用于传递反应性对象。
示例:考虑两个组件和这两个组件共享。
const Provider = {provide: {foo: 'bar'},template: `
简而言之,Vuex会主动更新从商店中读取数据的任何组件。
操作 - 状态接收到更改值以更改状态的位置。突变 - 实际状态发生变化的地方。考虑下面的例子。
注意:为了初始化商店,我创建了一个Vues.Store的新实例。
/* Store where the state is initialized and the values are mutated depending upon the values */var stateManager = new Vuex.Store {state: {state1: '', // Initialize the state1state2: '' // Initialize the state2}actions:{// API's can be called here and then accordingly can be passed for mutation},mutations: {changeStateOne(state, payload) {state.state1 += payload; // Recieved the payload from the action at the bottom},changeStateTwo(state, payload) {state.state2 += payload; // Recieved the payload from the action at the bottom.}}}// Component oneconst componentOne = {template: `
注意在操作:在上面的例子中,TGE动作是 increaseStatesValue() 正在提供所述有效载荷的功能 changeStateOne 和 changeStateTwo 功能,在突变部分。
上面的Vuex例子可以被映射在下面的图中。
在架构方面,Vuex使用flux作为它的方法。要了解通量,请检查flux patterns的文档。
我希望这篇文章提供了一些关于为什么在Vue应用程序中使用Vuex以及它如何在两个组件之间提供顺畅通信并促进状态之间的值更改的容易性的一些想法。
閱讀更多 愛碼農 的文章