vuex的使用入门-官方用例

store/index.js

import Vue from 'vue'
import Vuex from 'vuex';
// 使用vuex
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    count: 0
  },

  getters: {
    myCount(state) {
      return `current count is ${state.count}`
    }
  },

  mutations: {
    increment(state) {
      state.count += 1;
    },
    decrement(state) {
      state.count -= 1;
    }
  },

  actions: {
    myIncrease(context) {
      context.commit('increment')
    },
    myDecrease(context) {
      context.commit('decrement')
    }
  }

})
export default store;

Demo vuex

<template>
  <div class="container">
    <h1>{{ count }}</h1>
    <h1>{{ myCount }}</h1>
    <div>
      <button type="button" @click="increase">增加</button>
      <button type="button" @click="decrease">减少</button>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";

export default {
  name: "vuex",
  computed: {
    ...mapState(["count"]),
    ...mapGetters(["myCount"])
  },
  methods: {
    ...mapMutations(["increment", "decrement"]),
    ...mapActions(["myIncrease", "myDecrease"]),
    increase() {
      // this.$store.commit('increment')
      // this.increment();
      // this.$store.state.count += 1;
      this.myIncrease()
    },
    decrease() {
      // this.$store.commit('decrement')
      // this.decrement();
      // this.$store.state.count -= 1;
      this.myDecrease()
    }
  }
};
</script>

<style>
</style>

posted @ 2018-12-21 11:42  Ghost的前端日志  阅读(473)  评论(0编辑  收藏  举报