vuex基础学习


红色字体:专业术语太难记 便于记忆

1. Vuex

  • 一个专为 Vue.js 应用程序开发的状态管理模式。 数据仓库

1.1 最简单的使用Store

// 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)
//实例化一个new Vue.Stroe
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更

this.$store.commit('increment')     //触发mutation中的事件

this.$store.state.count			    //获取状态对象   在组建中使用
重点:很多忘记再根组件注册   就直接用this.$store  就会报错

在组建中使用this.$store…必须在根组件’注入’

const app = new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
components: { Counter },
template: `
 <div class="app">
   <counter></counter>
 </div>
`
})

1.2 三种属性

1.2.3 state 驱动应用的数据源;类似data()一样初始化

  • 设置状态属性
 state: {
   count: 0
 },
  • 在组建中获取状态属性computed
	computed :{
		count () {
		return this.$store.state.count
      }
	}
mapState辅助函数
不要想复杂了   这个函数就是为了让我们少按几个键盘,少写几行代码
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
 第1种写法   // 箭头函数可使代码更简练
    count: state => state.count,

 第2种写法  // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',

 第3种写法  // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}

当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。所谓 映射 就是在组件中 怎么使用

computed: mapState([
  // 映射 this.count 为 store.state.count   
  'count'
])
对象展开运算符 再次简化代码写法 不要紧张

详细示例讲解 …mapState

computed: {
  localComputed () { /* ... */ },
  // 使用对象展开运算符将此对象混入到外部对象中
  ...mapState({
    // ...
  })
}

1.2.4 mutations 能够改变state中值得的状态 唯一的方法 必须是同步操作

官方介绍:
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数:

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})
组件使用方法  this.$store.commit('increment')   触发increment回调函数
提交载荷(Payload)就是第二个参数
// count在state中定义:0
mutations: {
  increment (state, n) {
    state.count += n
  }
}
//组件中
this.$store.commit('increment', 10)
即:组件中触发一次  回调函数  count加10
this.$store.state.count=10;

官方称
在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读:

// ...
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
// 组件中触发事件并且传入一个对象
this.$store.commit('increment', {
  amount: 10
})
对象风格的提交方式
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
//组件中触发事件
this.$store.commit({
  type: 'increment',
  amount: 10
})
在组件中提交 Mutation的放方法 映射就是使用方法

官方
你可以在组件中使用 this.$store.commit(‘xxx’) 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

import { mapMutations } from 'vuex'

export default {
  // ...
  methods: {
    ...mapMutations([
第1方法
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
第2方法
      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
第3方法
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}

在 mutation 中混合异步调用会导致你的程序很难调试。例如,当你调用了两个包含异步回调的 mutation 来改变状态,你怎么知道什么时候回调和哪个先回调呢?这就是为什么我们要区分这两个概念。在 Vuex 中,mutation 都是同步事务

1.2.5 actions

常用    组件触发事件   '改变' state中数据  他让mutation成了一个中转站 用store.dispatch('increment')替代commit('increment')

官方
Action 类似于 mutation,不同在于:
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    increment (context) {
      context.commit('increment')
    }
  }
})

官方
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。
实践中,我们会经常用到 ES2015 的 参数解构 来简化代码(特别是我们需要调用 commit 很多次的时候):

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

组件触发事件方法

this.$store.dispatch('increment')

Actions 支持同样的载荷方式和对象方式进行分发:

// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

在组件中使用 Action和mutation一模一样

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}

官方
组合 Action
Action 通常是异步的,那么如何知道 action 什么时候结束呢?更重要的是,我们如何才能组合多个 action,以处理更加复杂的异步流程?
首先,你需要明白 store.dispatch 可以处理被触发的 action 的处理函数返回的 Promise,并且
store.dispatch 仍旧返回 Promise:

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}
//组件中
this.$store.dispatch('actionA').then(() => {
  // ...
})

// 另一个组件中
actions: {
  // ...
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

组合没太理解 等待指教

// 假设 getData() 和 getOtherData() 返回的是 Promise

actions: {
  async actionA ({ commit }) {
    commit('gotData', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('gotOtherData', await getOtherData())
  }
}

1.2.6 Getter 公共计算区

书写方法

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)
    }
  }
})

组件使用方法

store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}

mapGetters 辅助函数
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:


import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值