5.vuex学习之acrions、mapActions

Action 类似于 mutation,不同在于:

  1.Action 提交的是 mutation,而不是直接变更状态。

  2.Action 可以包含任意异步操作。

在store.js中

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//访问状态对象
const state = {
    count:1,
    age:10
}

// 触发的状态,mutations是同步的
const mutations = {
    jian(state){
        state.count--
    },
    jia(state,n){
        state.count+=n.a
    }
}// actions是异步的 异步的批处理触发集合,可以调用mutations里面的方法
const actions = {
   jiaplus(context){//context代表整个store
        context.commit('jia',{a:10})
   },
   jianplus({commit}){
       commit('jian')
   }
}


export default new Vuex.Store({
    state,
    mutations,
   actions
})

在App.vue中

<template>
  <div id="app">
    
    <img src="./assets/logo.png">
    <h1>{{ msg}}</h1>
    <!--访问状态对象-->
    <div>{{$store.state.count}}</div>
    <!--用commit访问触发的mutations里面的方法-->
    <button @click="$store.commit('jia',{a:10})">+</button>
    <!--使用mapMutations-->
    <button @click="jian">-</button>
    <p>
      mapActions
      <button @click='jiaplus'>+</button>
      <button @click='jianplus'>-</button>
    </p>
  </div>
</template>

<script>

//vuex提供的辅助函数
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
export default {
  name: 'app',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  
  // computed:{
  //   count(){
  //     return  this.$store.state.count //this指的是store
  //   }
  // },

  // computed:mapState({
  //   count:state=>state.count++
  // })
  
  // 不对computed进行计算,count直接引进来
  computed:{
    ...mapState([
      'count'
    ]),
    // count(){
    //   return this.$store.getters.count
    // }
    ...mapGetters([
      'age'
    ])
  },
  // methods:mapMutations([
  //   'jian'
  // ])
  methods:{
    ...mapMutations([
      'jian'
    ]),
    ...mapActions([
      'jiaplus'
    ]),
    ...mapActions({
      jianplus:'jianplus'
    })
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}
</style>

猜你喜欢

转载自www.cnblogs.com/tw6668/p/9107502.html