vuex复习篇

先来个极简版本的按钮计数器

如官网所述,状态更改方法写在store里

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const store= new Vuex.Store({
  state: {
    count:0
  },
  mutations: {
    increment(state){
      state.count++
    },
    decrement(state){
      state.count--
    }
  },
});
export default store

在页面上用$store.commit()去使用方法

<template>
  <div>
    <h1>我是组件</h1>
    <button @click="$store.commit('increment')">+</button>
    <span>{{$store.state.count}}</span>
    <button @click="$store.commit('decrement')">-</button>
     </div>
</template>

<script>
import store from '../store'
export default {
  store,
  name:"HelloWorld",
  data(){
    return{
      count:0
    }
  },
}

效果图
在这里插入图片描述

升级版本

主要引用辅助函数,去简写标签里的方法

<template>
  <div>
    <h1>我是组件</h1>
    <button @click="increment">+</button>
    <span>{{count}}</span>
    <button @click="decrement">-</button>
     </div>
</template>

<script>
import store from '../store';
import {mapState, mapMutations} from 'vuex';

export default {
  store,
  name:"HelloWorld",
  data(){
    return{
      // count:0
    }
  },
  computed:
  // 方法一  计算属性
  // {
  //   count(){
  //     return this.$store.state.count
  //   }
  // }
  // 方法二 mapState  辅助函数
  // mapState({
  //   count:function(state){
  //     return state.count
  //   }
  // })
  // 方法三 数组 照这么写  数组方法最简洁
  mapState(['count']),
  methods:mapMutations(['increment','decrement'])
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值