npm install vuex --save-dev
在vue項目目錄下創建store文件夾vue
須要在項目main.js文件中引入storevuex
import store from './store/index' 省略代碼..... new Vue({ el: '#app', router, store, data:{}, components: { App }, template: '<App/>' })
接下來在store中,創建如下目錄文件npm
import Vue from 'vue' import Vuex from 'vuex' import logIn from './modules/logIn' Vue.use(Vuex);
引入vue和vuex,還有狀態文件logIn.jssession
const state = {} const actions = {} const mutations = {} const store = new Vuex.Store({ modules: { logIn }, actions, state, mutations, }) export default store; 在logIn.js中寫入須要的狀態 // initial state const state = { session_id: "", user: "", userImage:"" } const getters = {} const actions = {} const mutations = { getSession_id(state, value) { state.session_id = value; }, getUser(state, value) { state.usermobile = value; }, getUserImage(state, value) { state.userImage = value; }, } export default { namespaced: true, state, getters, actions, mutations }
在使用的時候,要修改logIn.js中session_id的值,能夠這樣改變app
$this.$store.commit("logIn/getSession_id", res.data.session_id);
若是想獲取session_id的值,能夠這樣this
computed:{ session_id(){ return this.$store.state.logIn.session_id; }, }
到此,vuex就能夠在項目中使用了。spa