vuex流程简单示例

在vue-cli中使用vuex(个人理解实现数据的公用):

1.安装vuex,在vue-cli目录下的src文件下建立vuex目录=》vuex文件夹下建立store.js文件,文件如下:
 

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

const state={
  count:1
}

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

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

2,在components目录下建立Count.vue组件,代码如下

<template>
<p>{{$store.state.count}}</p>
<p>{{count}}</p>
<button @click="$store.commit(add,10)"></button>
<button @click="$store.commit(reduce)"></button>


<button @click="add"></button>
<button @click="$reduce"></button>

</template>

<script>
import store from "../vuex/store.js"
import {mapMotutions} from 'vuex'

export default{
   data(){
     return {
         msg:"学习vuex"
     }
   },
   computed:count(){
     return this.$store.state.count    //computed:mapState(['count'])
   },
   methods:{
     mapMutations(['add','reduce'])
   },         
   store
}
</script>

注:除了利用computed的计算变量来实现count,还可以了解以下vuex的mapState()简化变量的引用,mapMutation()简化方法的引用,其他诸如getter以及mapGetter()等状态的过滤使用中可以进行了解,另外action以及module等部分可以使用中理解,目前我的工作中使用对于这一块使用较少

3,认真理解其生命周期

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值