vuex
(一)vuex是什么?Vuex 是一個專為 Vue.js 應用程序開發(fā)的狀態(tài)管理模式
(二)適用場景?構(gòu)建是一個中大型單頁應用
(三)優(yōu)缺點:
優(yōu)點:采用集中式存儲管理應用的所有組件的狀態(tài)
缺點:如果開發(fā)小型單頁應用,使用 Vuex 可能是繁瑣冗余
(四)其他方案:如果開發(fā)小型單頁應用,一個簡單的 global event bus 就足夠您所需了
(五)說一下如何實現(xiàn)?要么說代碼,要么說思路
第一步:安裝vuex
npm install vuex --save
第二步:創(chuàng)建一個store目錄,并在內(nèi)部創(chuàng)建一個index.js
// 在index.js引入下面內(nèi)容:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
//創(chuàng)建存儲數(shù)據(jù)的倉庫state,集中管理數(shù)據(jù)
const state={
msg:"1509A"
}
//actions中的方法,這里面的方法都是異步操作
const actions={
setValue(context,res) {
// console.log(res);
context.commit('setData',res);
}
}
//創(chuàng)建mutations,目的是能最終改變倉庫中的數(shù)據(jù),這里是同步操作
const mutations={
setData(state,result) {
state.msg=result;
}
}
//暴露出去
export default new Vuex.Store({
state,
actions,
mutations
})
第三步:在main.js中引入store中的index.js,并在Vue的實例中注冊
引入:
import store from './store'
注冊:
new Vue({
....
store,
....
})
第四步:在組件中如何獲取/改變倉庫中的數(shù)據(jù)
獲取數(shù)據(jù)狀態(tài):要在computed計算屬性中獲取數(shù)據(jù)狀態(tài),例如:
computed:{
aa() {
return this.$store.state.msg
}
}
改變數(shù)據(jù)狀態(tài):
觸發(fā)一個事件,然后再事件方法中用dispath派發(fā)到actions
html部分:
<button @click="go">將發(fā)送給B組件</button>
js部分:
methods:{
go() {
//this.$store.dispatch('actions方法名','要改變的值')
this.$store.dispatch('setValue',this.info)
}
},
通過commit提交到mutations對應方法