Vuex 使用方法

1、什么是Vuex
Vuex 是一個專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式。
官網(wǎng):https://vuex.vuejs.org/zh/
gitHub:https://github.com/vuejs/vuex

strict:嚴格模式 可使用 process.env.NODE_ENV !== 'production'
state:存儲狀態(tài)
mutations:專門修改state數(shù)據(jù)
actions:組合mutations完成負責(zé)操作
getters:類似computed 判斷是否登錄等

2、安裝
npm i vuex

在項目中新建store文件夾,在文件夾下創(chuàng)建actions、getters、mutations、index JS文件


image.png
store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import * as getters from './getters';
import * as mutations from './mutations';
import * as actions from './actions';

Vue.use(Vuex);

let locale = localStorage.getItem('locale') || "zh"
const state = {
  locale,
};

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
});
store/actions.js
export const setLocale = ({ commit }, data) => {
  commit('setLocale', data);
};
store/getters.js
export const locale = state => state.locale;
store/mutations.js
export const setLocale = (state, data) => {
  state.locale = data;
};
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/index';
Vue.prototype.$store = store
Vue.config.productionTip = false

new Vue({
    store,
    router,
    i18n,
    render: h => h(App)
}).$mount('#app')
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容