什么是Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
创建/src/store
目录,然后在main.js
中加入如下代码:
import store from './store'
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
使用例子
在/src/store/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,
getters: {
doubleCity (state) {
return state.city + ' ' + state.city
}
}
})
然后我们在/src/store
目录下创建state.js
,mutations.js
state.js
中代码:
let defaultCity = '上海'
try {
if (localStorage.city) {
defaultCity = localStorage.city
}
} catch (e) {}
export default {
city: defaultCity
}
mutations.js
中代码:
export default {
changeCity (state, city) {
state.city = city
try {
localStorage.city = city
} catch (e) {}
}
}
在某个组件中使用映射
<div class="button">{{this.currentCity}}</div>
import {mapState, mapMutations} from 'vuex'
computed: {
...mapState({
currentCity: 'city'
})
},
methods: {
handleCityClick (city) {
this.changeCity(city)
this.$router.push('/')
},
...mapMutations(['changeCity'])
},
网友评论