Vuex store 的使用

赚钱好难啊啊啊啊,祝我早日财富自由,开个小卖部~节后第一天,先码篇帖子,只要我够努力,一定会让老板过上想过的生活~

Store的代码结构一般由StateGettersMutationActions这四种组成,也可以理解Store是一个容器,Store里面的状态与单纯的全局变量是不一样的,无法直接改变store中的状态。想要改变store中的状态,只有一个办法,显示地提交mutation。

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count:1
  },
  getters:{

  },
  mutations: {
    addmu(state){state.count++},
    lessmu(state){state.count--}
  },
  actions: {
   
  }
})
<template>
  <div class="hello">
    <h1>{{ this.$store.state.count }}</h1>
    <div>
      <button @click="addfn()">增加</button>
      <button @click="lessfn()">减少</button> 
    </div>
 
  </div>
</template>
 
<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  methods:{
    addfn(){
       //提交名为addmu的mutations
       this.$store.commit('addmu');
    },
    lessfn(){
       //提交名为lessmu的mutations
       this.$store.commit('lessmu');
    }
  }
}
</script>

由于mutation必须同步执行的限制,不方便实现复杂的功能。不过,别担心,看见了那个Actions吗?它就不受约束!我们可以在 它内部执行异步操作

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count:1
  },
  getters:{

  },
  mutations: {
    addmu(state){state.count++},
    lessmu(state){state.count--}
  },
  actions: {
    addac({commit}){commit('addmu')},
    lessac({commit}){commit('lessmu')}
  }
})
<template>
  <div class="hello">
    <h1>{{ this.$store.state.count }}</h1>
    <div>
      <button @click="addfn()">增加</button>
      <button @click="lessfn()">减少</button> 
    </div>
 
  </div>
</template>
 
<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  methods:{
    addfn(){
       //以载荷方式分发
       this.$store.dispatch('addac');
    },
    lessfn(){
       //以对象方式分发
       this.$store.dispatch({type:'lessac'});
    }
  }
}
</script>

文章转自vuex的Store简单使用过程 - 木人子韦一日尘 - 博客园 (cnblogs.com)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值