在上篇文章中,我们简单的使用了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升级版的使用了。
有哪里写的的不对的地方,及时指正!共同学习,共同成长!