1、Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
2、Vuex 采用集中式存储和管理应用中所有组件的状态
3、Vuex 应用的核心是 store(仓库)-- 包含 state(组件中的共享状态)和 mutations(改变状态的方法)
npm install vuex --save
import store from './store'
state 可以看作是所有组件的 data,用于保存所有组件的公共数据。
getters 可以看作是所有组件的 computed 属性,getters 的返回值会根据它的依赖被缓存起来,只有当它的依赖值发生改变才会被重新计算。
mutations 可以看作是 store 中的 methods,其中保存着更改数据的回调函数。
actions 类似于 mutations,区别在于:
由于使用单一状态树,当应用变得非常复杂时,store 对象会变得相当臃肿,Vuex 允许将 store 分割成模块(module)。每个模块拥有自己的 state、mutations、actions、getters、甚至是嵌套子模块——从上至下进行同样方式的分割:
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
通过 store.state 来获取状态对象,示例:
store.js 文件:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
num: 1
},
mutations: {
changeFunction (state, num) {
state.num++
}
}
})
main.js 文件:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
views/demo.vue 文件:
<template>
<div>
<p>{{msg}}</p>
<button @click="getNum">getNum</button>
</div>
</template>
<script>
export default {
data () {
return {
msg: '0'
}
},
methods: {
getNum () {
this.msg = this.$store.state.num
}
}
}
</script>
运行效果:
通过 store.commit 方法触发状态变更,示例:
store.js 文件:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
num: 1
},
mutations: {
changeFunction (state, num) {
state.num++
}
},
actions: {
changeNum ({ commit }, obj) {
commit('changeFunction', obj)
}
}
})
main.js 文件:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
views/demo.vue 文件:
<template>
<div>
<p>{{msg}}</p>
<button @click="getNum">getNum</button>
<button @click="changeNum">changeNum</button>
</div>
</template>
<script>
export default {
data () {
return {
msg: '0'
}
},
methods: {
getNum () {
this.msg = this.$store.state.num
},
changeNum () {
this.$store.dispatch('changeNum', 100000)
this.msg = this.$store.state.num
}
}
}
</script>
运行效果: