Vuex状态管理模式
当两个或两个以上的组件需要共用同一个数据源时,使用Vuex对数据的管理会变得更见简单轻松(相比localStorage、路由传参)
响应式
Vuex的状态存储是响应式的。当Vue组件从store中读取状态的时候,若store中的状态发生变化,那么相应的组件(视图)也会相应地得到高效更新。
核心概念
- state
- getters
- mutations
- actions
state
存放共享的数据,需要提前声明
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 0
}
})
// main.js,注入store,每个组件都可以通过this.$store访问store
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/store'
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
如何在组件中获取state中的数据?
- 直接调用
let count = this.$store.state.count
this.count = count
<span>{
{count}}</span>
- 计算属性
// 由于Vuex的状态存储是响应式的,从store实例中读取状态最简单的方法就是在计算属性中返回某个状态
// 每当 store.state.count 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM
computed: {
count () {
return this.$store.state.count
}
}
<span>{
{count}}</span>
- mapState辅助函数
// 当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。
// 为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:
// 不用写那么多次this.$store.state.xxx
import { mapState } from 'vuex'
export default {
// mapState函数传入一个对象
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count