前面的話
前端日問,鞏固基礎,不打烊!!!
解答
組件之間的通信方式有很多種,Vuex解決了非父子組件通信消息傳遞,一般適合用於大項目,如果項目不大,涉及的組件通信方式不多,可以採用$.attrs
與$.listeners
.
Vuex:是Vue的狀態管理器,用來存儲數據,並且數據都是響應式的。
Vuex的原理介紹
通過new Vuex.Store()來創建一個store實例,store實例有5大屬性,分別是state、mutations、actions、getters,mudules
const store = new Vuex.Store({
state:{
},
mutations:{
},
actions:{
},
getters:{
}
})
new Vue({
store,
render: h => h(App),
}).$mount('#app')
-
state: 用來提供響應式數據,在組件中通過使用
this.$store.state.xxx
來讀取state裏面的數據。(Vuex的state狀態是響應式,是藉助vue的data是響應式,將state存入vue實例組件的data中 ) -
mutations:在組件中,想要改變state中的數據,唯一的方法就是觸發
mutations
來改變。使用this.$store.commit()
來執行mutations。const store = new Vuex.Store({ state: { count: 0 }, mutations: { increments(state) { state.count++; } } })
通過在組件中使用:
this.$store.commit('increments')
來觸發mutations中的increments事件的執行。但它只能同步執行,不適合異步。 -
getters : 依賴於state裏的數據, 可理解爲一個計算屬性.(Vuex的getters是藉助vue的計算屬性computed實現數據實時監聽)
const store = new Vuex.Store({ state: { list: [1,5,8,10,30,50] }, getters: { filteredList: (state) => { return state.list.filter(item => item < 10); } } })
通過
this.$store.getters.filteredList
來訪問數據。 -
actions: 用來操作異步,如果想異步操作數據就要使用actions,但它不能直接修改,最終還是要通過mutations來操作。
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state, n=1){ state.count += n; } }, actions: { asyncIncrement(context){ return new Promise((reslove) => { setTimeout(() => { context.commit('increment', 2); resolve(); },1000) }) } } })
在組件這樣使用 :
this.$store.dispatch('asyncIncrement').then(()=> { console.log('this.$store.state.count'); })
-
modules: 是store分割的模塊,每個模塊擁有自己的state、getters、mutations、actions。
const moduleA = { state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... } } const moduleB = { state: { ... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB } }) store.state.a // -> moduleA 的狀態 store.state.b // -> moduleB 的狀態