action和mutation基本类似:
action提交的是mutation,不是直接更改state的状态,而mutation是直接修改state状态action可以包含任意的异步操作,比如ajax请求简单注册一个action
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { num: 0, name: '刘国旭', age: 22, getters: '用使的retteg是这', mapGetters: 'mapGetters', duanzi: null, }, // 就是公共的计算属性 //getters: { // getterMsg: function(state) { // return state.getters.split('').reverse().join('') // }, // mapGetters: function(state) { // return state.mapGetters // } //}, //mutations: { // numAdd(state) { // state.num += 2; // }, // setNum(state, value) { // state.num = value; // }, // setDuanzi(state, value) { // state.duanzi = value; // } //}, // 异步方法 actions: { setDz: function(context) { let httpUrl = 'https://api.apiopen.top/getJoke?page=1&count=20&type=video' fetch(httpUrl).then(res => res.json()).then(res => { let data = res.result if (res.code === 200) { context.commit('setDuanzi', data) } else { console.log(message) } }) } }, modules: { } })上面代码我们再action里面做了一个ajax请求。
action函数接受一个context属性,我们可以调用context.commit()提交一个mutation,也可以输出一下context,可以获取到state和getters。
<template> <div class="action"> <button @click="getDuanzi">点击获取段子</button> <ul> <li v-for="(item,index) in duanzi" :key="index"> <h2>{{item.text}}</h2> <video width="500px" height="300px" :src="item.video" :poster="item.header" controls></video> </li> </ul> </div> </template> <script> import { getlbt } from '@/api/data'; import { mapState,mapActions } from 'vuex'; export default { name: 'action', // 测试axios封装 // async mounted() { // let res = await getlbt() // console.log(res.msg) // }, methods: { // getDuanzi:function(){ // this.$store.dispatch('setDz') // }, // 使用辅助函数将 this.getDuanzi 映射为 this.$store.dispatch('setDz') ...mapActions({ getDuanzi: 'setDz' }) }, computed: { ...mapState({ duanzi: 'duanzi' }), }, } </script>上面代码我们使用辅助函数 mapActions 将 this.getDuanzi 映射为 this. s t o r e . d i s p a t c h ( ′ s e t D z ′ ) , 也 可 以 使 用 注 释 起 来 的 t h i s . store.dispatch('setDz'),也可以使用注释起来的 this. store.dispatch(′setDz′),也可以使用注释起来的this.store.dispatch(‘setDz’) 去分发action
我们可以通过 this.$store.dispatch(‘xxx’) 分发action,或者使用 mapAction 辅助函数将组件的 methods 映射为 store.dispatch 调用,注意要引入
import {mapAction} from 'vuex' import {mapAction} from 'vuex' methods: { ...mapActions([ 'setDz', // 将 `this.setDz()` 映射为 `this.$store.dispatch('setDz')` ]), ...mapActions({ add: 'setDz' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')` }) }更过方法可以查看官方文档
可以点击此处GitHub地址查看完整项目代码