vuex学习之Actions的用法详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vuex学习之Actions的用法详解

风起了--   2020-05-16 我要评论

Action 类似于 mutation,不同在于:

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

沿用vuex学习---简介的案例:这里是加10 减1

1.在store.js 中 代码为:

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

//使用vuex模块
Vue.use(Vuex);

//声明静态常量为4
const state = {
  count : 4
};

const mutations = {
  add(state,n){
    state.count +=n.a;
  },
  sub(state){
    state.count--;
  }
};

const actions = {
  //2种书写方式
  addplus(context){ //可以理解为代表了整个的context
    context.commit('add',{a:10}) 
  },
  subplus({commit}){
    commit('sub');
  }
};

//导出一个模块
export default new Vuex.Store({
  state,
  mutations,
  actions
})

2.在App.vue中 代码如下:

<template>
 <div id="app">
   <div id="appaaa">
    <h1>这是vuex的示例</h1>

    <p>组件内部count{{count}}</p>
    <p>
      <button @click = "addplus">+</button>
      <button @click = "subplus">-</button>
    </p>
    </p>

  </div>
 </div>
</template>

<script>
//引入mapGetters 
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
export default {
 name:'app',
 data(){
   return {
     
   }
 },
 computed:{
   ...mapState([
     "count"
     ]),
 },
 methods:{
   ...mapActions([
      "addplus",
      "subplus"
     ])
 }

}
</script>

<style>

</style>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们