討論組件之間如何大規模共享數據,以及使用Vue / Vuex應用程序的示例代碼。
Vue作為一個漸進式框架,在語法方面與Angular相似。為了理解Vue中的組件以及Vuex的用途,首先,我們將介紹Vue如何提供在組件之間共享數據的能力。
什麼是組件?為什麼我們需要在組件之間共享數據?如果您熟悉Angular指令,那麼它就像一個簡單的指令,我們可以編寫自己的邏輯,提供模板(模板),並調用該組件(而不是將組件註冊到根實例)。
示例:
//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以及它如何在兩個組件之間提供順暢通信並促進狀態之間的值更改的容易性的一些想法。
閱讀更多 愛碼農 的文章