什么是Vuex
Vuex 是一個(gè)專為 Vue.js 應(yīng)用程序開發(fā)的狀態(tài)管理模式
vuex.png
創(chuàng)建/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
目錄下創(chuàng)建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) {}
}
}
在某個(gè)組件中使用映射
<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'])
},