vuex的分解优化使用

在上篇文章中,我们简单的使用了vuex,现在对它进行分解优化。

1.创建一个store的文件夹

在main.js中引用这个store文件夹:

import store from './store'

new Vue({
  el: '#app',
  store
})

在store文件中创建index.js、mutations.js和state.js。
index.js:

import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'

Vue.use(Vuex)

export default new Vuex.Store({
  state,
  mutations
})

mutations.js:

export default {
  changeCity (state, city) {
    state.city = city
    try {
      localStorage.city = city
    } catch (e) {}
  }
}

state.js:

let defaultCity = '上海'
try {
  if (localStorage.city) {
    defaultCity = localStorage.city
  }
} catch (e) {}

export default {
  city: defaultCity
}

2.在一个城市列表组件中,使用了changeCity 方法、city属性,而且我们还使用了2个辅助函数:
mapState 辅助函数帮助我们生成计算属性。当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

<div class="button">{{this.currentCity}}</div><div class="button">{{this.city}}</div>

import { mapState, mapMutations } from 'vuex'
<script>
computed: {
  // 映射 this.currentCity 为 store.state.city
  ...mapState({
    currentCity: 'city'
  })
 // 或是采用下边这种方式
 // 映射 this.city 为 store.state.city
 ...mapState(['city'])
},
methods: {
  handleCityClick (city) {
    // 这里跳过了actions(dispatch命令),直接使用mutations(commit命令)
    // this.$store.dispatch('changeCity', city)
    // this.$store.commit('changeCity', city)
    // this.changeCity(city)
    this.cityChange(city)
    this.$router.push('/')
  },
  // 将 `this.changeCity()` 映射为 `this.$store.commit('changeCity')`
  // ...mapMutations(['changeCity'])
  // 或是采用下边这种方式
  // 将 `this.cityChange()` 映射为 `this.$store.commit('changeCity')`
  ...mapMutations({
    cityChange: 'changeCity'
  })
}
</script>

这就是vuex升级版的使用了。
有哪里写的的不对的地方,及时指正!共同学习,共同成长!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值