本文主要包含vue-vuex等相关知识,u014196765希望在学习及工作中可以帮助到您
  1,在vue-cli中加载vuex,在项目中按住shift,点击右键,调出命令行输入框。输入命令
npm install vuex --save-dev
2,在项目中引用vuex。建一个文件 叫 store.js
/**
 * Created by Administrator on 2017/9/18.
 */
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const store = new Vuex.Store({
  state:{
    type: '',
  },
  getters:{
    getType:function (state) {
      if(!state.type){
        state.type = localStorage.getItem('type')
      }
      return state.type;
    }
  },
  mutations:{
    //格式:类型(名字)+处理函数
    //加1
    changetype(state,type) {
      //console.log(state)//state对象
      state.type = type;
    }
  },
  actions:{
   /* increment({commit}){
      commit("INCREMENT")
    }*/
  }
})
export default store
然后在main.js中引用store.js
import store from  './assets/js/store'
同时在vue下注册
new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})
3,vuex已经引入成功了,下面就是如何使用vuex了。
有两种方法可以type的值。
a、直接调用type更改
this.$store.state.type = 'aaa'
b、调用vuex的commit函数,官网更推荐这种方式。
this.$store.commit('changetype','aaa')
changetype上面的store.js里已经定义了
此时type的值就变为了aaa
4,获得type的值,也有两种方法。
a、直接拿到type的值
this.$store.state.type
b、使用getter方法
this.$store.getters.getType
下面是我用vuex时遇到的一个坑。
vuex刷新时数据丢失。
对于一个程序来说,整个页面都是变量,刷新页面数据当然会丢失,解决方案就是使用localStorage,sessionStorage等。如代码,如果页面没有type的值,就用localStorage在设置一下type值
getters:{
    getType:function (state) {
      if(!state.type){
        state.type = localStorage.getItem('type')
      }
      return state.type;
    }
  },
  
 
