Vuex is a specially developed for Vue.js application state management . It uses the status of all components centralized storage management application, and a corresponding state rules to ensure a predictable manner changed.
installation
npm install vuex --save
main.js
import store from './store'
new view ({
router,
store,
render: h => h(App)
}).$mount('#app')
store.js
Import view from 'View'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {// the data source vuex
userInfo: (sessionStorage.userInfo) ? JSON.parse(sessionStorage.userInfo) : null,
count: 1, // this.$store.state.count获取
list: [{ id: 1, name: 1 }, { id: 2, name: 2 }, { id: 3, name: 3 }]
},
getters: {// corresponding to the computed vue
getStateCount: state => { // this.$store.getters.getStateCount获取
return state.count + 1
},
getNewList: state => { // this.$store.getters.getNewList获取
return state.list.filter(n => n.id < 3)
}
},
mutations: {
getUserInfo (state, n) { // this.$store.commit('getUserInfo',n)
state.userInfo = n
sessionStorage.userInfo = JSON.stringify(n)
}
},
actions: {// registered actions, in the methods similar vue
getUserInfoFun (content, n) {// accepts a right home and store the same manner as the example of content attribute objects this. $ store.dispatch ( 'getUserInfoFun', n)
content.commit('getUserInfo', n)
}
}
})
mapState、mapGetters、mapActions
In vue first reference file
import { mapState, mapGetters, mapActions } from "vuex";
Then get
computed: {
...mapState({
count1: state => state.count
})
},
references
Vuex :https://vuex.vuejs.org/zh/
5 Minute you started vuex ( VUE state management ):
https://baijiahao.baidu.com/s?id=1618794879569468435&wfr=spider&for=pc