一:store:vueX的核心
我们可以将store认为是一个仓库,这个仓库中保存着组件之间共享的数据 state和方法
1,state
在store中存在这state,这里面保存着所有组件之间共享的数据:这里面的状态是响应式的,如果store中的状态得到变化,那么相应的组件的状态也会得到变化;
2,mutations
我们通过mutations来实现改变store中的state
我们通过 store.state来获取状态对象,我们通过 store.commit来触发状态更新
二:读取store对象:
我们如何读取store对象呢?
在store实例中读取状态的方法是在计算属性中返回某个状态;
代码如下:
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
我们在根实例中注入store对象,然后在子组件中通过 this.$store来访问到:
this.$store.state来访问到状态;
但是这种方法只能获取一种状态,但我们需要获取到多种状态的时候,我们通过 mapstate来获得:
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
如上:
三:getters:
getters是用于计算state的函数,这实际上是函数,使用这个函数我们可以对state进行处理:
代码如下:
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
如上:
这段代码的意思是 对于state中的todos进行处理:
调用:
store.getters.doneTodos
或者在组件中调用:
computed: {
doneTodosCount () {
return this.$store.getters.doneTodos
}
}
如上:
mapGetters用于将store中的getters映射到局部属性:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getters 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
完: