vuex
#vuex简介
1.状态管理模式
new Vue({
// state
data () {
return {
count: 0
}
},
// view
template: `
<div>{
{ count }}</div>
`,
// actions
methods: {
increment () {
this.count++
}
}
})
这个状态自管理应用包含以下部分
state:驱动应用的数据源
view:以声明方式将state映射到视图
actions:响应在view上的用户输入导致的状态变化
2.集中式存储管理应用的所有组件的状态
3.Vuex使用单一状态数,用一个对象就包含了全部的应用层级状态
4.唯一数据源,每个应用中仅仅包含一个store实例
5.vuex的状态是响应式的
#State
1.在vue中获得vuex状态
从 store 实例中读取状态最简单的方法就是在计算属性中返回某个状态,每当 store.state.count
变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。
// 创建一个 Counter 组件
const Counter = {
template: `<div>{
{ count }}</div>`,
computed: {
count () {
return store.state.count
}
}
}
Vuex 通过 store
选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)
):
const app = new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
components: {
Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
})
通过在根实例中注册 store
选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store
访问到。让我们更新下 Counter
的实现:
const Counter = {
template: `<div>{
{ count }}</div>`,
computed: {
count () {
//子组件内通过$store.state.访问
return this.$store.state.count
}
}
}
2.mapState辅助函数
// 在单独构建的版本中辅助函数为 Vuex.mapState
import {
mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,
//count:function(state){return state.count}
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数,不能使用
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState
传一个字符串数组。
computed: mapState([
// 映射 this.count 为 store.state.count
'