Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化
// store.js
/*
vuex的核心管理对象模块:store
*/
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 状态对象
const state = { // 初始化状态 这里放置的状态可以被多个组件共享
count: 1,
name: 'daming'
}
const mutations = {}
const action = {}
const getters = {}
export default new Vuex.Store({
state, // 状态
mutations, // 包含多个更新state函数的对象
actions, // 包含多个队形事件回调函数的对象
getters // 包含多个getter计算属性函数的对象
})
// main.js
/*
入口JS
*/
import Vue from 'vue'
import App from './App.vue'
import store from './store'
// 创建vm
/* eslint-disable no-new */
new Vue({
el: '#app',
components: {App}, // 映射组件标签
template: '<App/>', // 指定需要渲染到页面的模板
store // 所有的组件对象都多了一个属性:$store
})
- 标准获取state
import { mapState } from 'vuex' // 引入mapState
computed: {
// 常规 computed
tempCountPlusTempCount2() {
return this.tempcount+this.tempcount2
}
// 由于 Vuex 的状态存储是响应式的,所以可以使用计算属性来获得某个状态
// 当状态改变时,都会重新求取计算属性,并且触发更新相关联的 DOM
// 通过下面的计算属性,就可以在当前组件中访问到count,name,nameAlias等了
// 在模板中我们通过大括号符号打印出来
// vuex管理的状态 computed
count () {
return this.$store.state.age
},
name () {
return this.$store.state.age
},
nameAlias () {
return this.$store.state.name
}
countplustempcount: function (state) {
return this.tempcount + this.$store.state.count
},
countplustempcount2 (state) {
return this.tempcount2 + this.$store.state.count
}
}
但有一个问题,当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。比如上面的name(),count(),nameAlias(),显得重复,代码冗长为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少按几次键:
mapState函数可以接受一个对象Object<string | function>。对象中可以包含字符串或函数。mapState()函数的返回结果是一个对象。
<script>
import { mapState } from 'vuex'
computed: mapState({ // 或者使用扩展运算符 ...mapState({ xxx })
count: 'count', // string 映射 this.count 为 store.state.count的值
// 箭头函数可使代码更简练
name: (state) => state.name, // function 映射 this.name 为 store.state.name的值
nameAlias: 'name', // string 映射 this.nameAlias 为 store.state.name的值
countplustempcount: function (state) {
// 用普通函数this指向vue实例,但是在箭头函数中this就不是指向vue实例了,所以这里必须用普通函数
return this.tempcount + state.count
},
countplustempcount2 (state) {
return this.tempcount2 + state.count
}
})
}
</script>
- mapState函数可以接受一个数组,当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给
mapState传一个字符串数组。
computed: mapState([
// 映射 this.count 为 store.state.count
'count',
'name'
])
等价于
computed: {
count () {
return this.$store.state.count
},
name () {
return this.$store.state.name
}
}