在vue中引入vuex

最近使用了一下vuex,下面是自己的心得,和遇到的坑。希望看到同学可以借鉴

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里已经定义了

 mutations:{
    //格式:类型(名字)+处理函数
    //加1
    changetype(state,type) {
      //console.log(state)//state对象
      state.type = type;
    }
  },

此时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;
    }
  },
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小~小

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值