vuex的使用

一、在项目中导入vuex

·npm install vuex 下载vuex

·在src文件夹下创建文件store、在store下 创建index.js 并输入 如图

 

·在main.js中引入 store文件 并在vue根实例上导入store  如图:

 

这部分可以在vue官网中查看

 

 

 

二、获取vuex中的值

this.$store.state.值的键名

(如:this.$store.state.Name)

 

三、改变vuex中的值

 (3.1部分可以跳过直接看3.2,也可以做了解)

3.1 在vue文件的事件中 this.$store.dispatch(‘事件名’,参数):如

this.$store.dispatch('changeName',e)

 

export default new Vuex.Store({

    state: {

        Name: '名字'

    },

    actions:{

        changeName (ctx, e) {

            ctx.commit('changeName2',e)

        }

    },

    mutations: {

        changeName2 (state, e) {

            state.Name = e

        }

    }

})

 

3.2、 跳过actions 组件可以直接调用mutations传值

 

this.$store.commit ('changeName',e)

 

store/index.js中:

export default new Vuex.Store({

    state: {

        Name: '名字'

    },

    mutations: {

        changeName (state, e) {

            state.Name = e

        }

    }

})

 

然后调用的时候直接输入 xxx = this.$store.state.Name  就获取到啦

 

3.3、 但是有的时候  页面一刷新 vuex中保存的值就清空了,这时我们就配合localStorage来保存我们的值,具体怎么实现的细节就不写了直接上例子:

 

(try_catch是用来防止浏览器不兼容的问题,由于项目小所以state和mutation的部分没有分两个页面来写)

 

import Vue from 'vue'

import Vuex from 'vuex'

Vue.use(Vuex)

 

let lng = 120.2 ,lat = 36.5'//

try {

  if (localStorage.lng) {

    lng = localStorage.lng

  }

  if (localStorage.lat) {

    lat = localStorage.lat

  }

} catch (e) {}

//调用时设置  this.$store.commit ('changeName',e)   获取时:this.$store.state.Name

export default new Vuex.Store({

  state: {

    lng:lng,// 经度

    lat:lat,// 纬度

  },

  mutations: {

    changelng(state, e) {

      state.lng = e

      try {

        localStorage.lng = e

      } catch (e) {}

    },

    changelat(state, e) {

      state.lat = e

      try {

        localStorage.lat = e

      } catch (e) {}

    },

  }

})

 

 

posted @ 2018-10-11 10:44  suisuisui  阅读(247)  评论(0编辑  收藏  举报