什么是vuex
vuex是专门用来管理vue.js应用程序中状态的一个插件。作用是将应用中的所有状态都放在一起,集中式管理。
安装vuex
cmd中 npm install vuex --save
在src文件中创建个store文件——>store文件创建index.js、state.js、actions.js、mutations.js
src:index.js:
import Vue from ‘vue’
import vuex from ‘vuex’
Vue.use(vuex)
export default new vuex.Store({
state:state.city,
actions:actions,
mutations:mutations
})
state.js:
let city = ‘上海’
if(localStorage.city){
try{
localStorage.city=city
} catch (e) {}
}
export default {
city: city
}
actions.js:
expot default {
actions: {
changeStore (ctx,city) {
ctx.commit(‘changeStore’,city)
}
}
mutations.js:
export default {
mutations:{
changeStore (state,city){
state.city = city
try{
localStorage.city = city
} catch (e) {}
}
}
在其他相关的组件中,需要添加@click = ‘handleStore(item.name)’
import {mapActions,mapState} from ‘vuex’
exoprt default {
methods: {
handleStore(city){
this.changeStore(city)
}
…mapActions([‘changeStore’])
},
computed: {
…mapState([‘city’])
// …mapState({currentCity:‘city’})
}