1. What is it
state
?
As mentioned in the previous article, it
Vuex
is to provide a warehouse, and there are many objects in the warehouse. Among themstate
is the storage place of the data source , which corresponds to the inside of the generalVue
object (the and corresponding to thedata
later mentioned ).actions
mutations
methods
Responsive book storage :
state
The data stored in it is responsive, andVue
components read datastore
from it . Ifstore
the data in the book changes, the components that depend on this data will also be updated. (here " state " = " data "), that is, the data and the view are synchronized.
2. Local state
Get:
Vue
Get data in the component, the most direct way can be obtained through the computed property;Components can still save local state : Although
Vuex
theStore
warehouse makes it more convenient for us to manage data at the same time, the code will also become verbose. The data of some components is strictly for their own use, we can put themstate
in the component itself as a local Data is used exclusively for this component, other components cannot.
3.
mapState
mapState
The role is to map the globalstate
sum to the computed property of the current component, .getters
computed
this.$store.state
Example of use
import {mapState} from 'vuex' export default { computer : mapState({ count: state => state.count, 'count' // 映射 this.count 为 store.state.count }) }
look at the source code
export function mapState (states) { const res = {} //定义一个对象 normalizeMap(states).forEach(({ key, val }) => { // normalizeMap()函数初始化states数据 res[key] = function mappedState () { return typeof val === 'function' // 判断val是否是函数 ? val.call(this, this.$store.state, this.$store.getters) // 若val是函数,将store的state和getters作为参数,返回值作为mapped State的返回值 : this.$store.state[val]}}) return res // 返回的是一个函数 } //初始化方法 ------------------------------------------------------------------------- function normalizeMap (map) { return Array.isArray(map) //判断state是否是数组 ? map.map(key => ({ key, val: key })) // 是数组的话,调用map方法,将每一个数组元素转换成{key,val:key} : Object.keys(map).map(key => ({ key, val: map[key] })) // 否则就是对象,遍历对象,将每一个val变成val:key }