vuex 使用过程+ ...mapState+...mapMutation + localStorage

vuex使用过程:   vuex官网连接

按照官网的过程:从components开始-> actions->mutations->改变state



创建一个src/store/index.js:


先引入:vuex, vue中使用插件是用Vue.use(vuex), 输出一个Vuex.Store实例

// state放公用数据

//action放 异步操作或者批量处理同步操作  (简单情况可跳过action直接到mutations)

两个参数:上下文环境, 传参---使用ctx.commit( , )方法去调用mutations里面的方法名.

// mutations放置用来改变数据的方法.更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。参数是state

//getters 类似computed方法,进行数据的计算


//modules 用来Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割,然后组合到一起:


使用过程:

组件里使用state里面的公共数据: {{this.$store.state.city}}

组件派发异步或批量事件给actions: this.$store.dispatch(' action函数名', 参数)

actions提交mutations来改变数据:this.$storage.commit('mutations函数名', 参数)




基本使用方法如上.但是一般会把各部分内容分开写(state,actions,mutations,modules,getter),统一到store/index.js文件里:







vuex高级使用:

直接使用:


高级使用: ...mapState  ...mapMutations  ...mapGetters

扩展运算符...mapState,意思是把vuex的state数据映射到计算属性里面,映射后的名字为city,所以上面直接用this.city,就不用写this.$store.state.city这个长串了     

/src/pages/home/components/header.vue

1....mapState



2....mapMutations使用

src/pages/city/components/list.vue

...mapMutation把本组件的mutations映射到changeCity方法里(changeCity在mutations里)

之前写法是this.$store.commit('changeCity',city)

引入之后的写法:

localStorage用法:直接使用

注意:要用  try(){}catch(e){}包裹使用,因为有的浏览器会禁用localStorage或者不能用

let defaultCity = "北京"

try{
    if(localStorage.city){ 
     defaultCity = localStorage.city
    }

} catch (e){}

try{
localStorage.city = city
}catch(e){}