For example, use TypeScript+VueX for simple point-and-click increments

1. Write the state and mutations/SRC /store/index.js files as follows

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

Vue.use(Vuex) // Bind store to vue.prototype
export default new Vuex.Store({
  // Equivalent to data in vue
  state: {
    count: 0,},// Equivalent to methods in vUE
  mutations: {
    vuexAdd(state) {
      state.count ++
    },
  },
})

Copy the code

2. Load the Store folder in main.ts

import Vue from 'vue'
import App from './App.vue'
import store from './store'


new Vue({
  store,
  render: (h) = > h(App),
}).$mount('#app')
Copy the code

3. Use in test.vue

<template>
  <div>
	{{ count }}
       <button  @click="add">I + 1 point</button>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { Component } from 'vue-property-decorator'
import Button from '@/components/Button.vue'

@Component({
  computed: {
  // We are using data in Vuex, best defined in computed attributes, so changes can be updated in real time
    count() {
    // Vuex state is used
      return this.$store.state.count
    },
  },
})
export default class test extends Vue {
  add() {
  // vuexAdd method defined in Vuex achieves +1 function
    this.$store.commit('vuexAdd')}}Copy the code

After the click:

There is a problem above. Vuex data obtained in computed data can only be used in template template, and errors will be reported if it is used in the script below. After half an hour of consulting the document, I will find a solution in Vue Class Component, which is to use the GET method of ES6

So our


 computed: {
  // We are using data in Vuex, best defined in computed attributes, so changes can be updated in real time
    count() {
    // Vuex state is used
      return this.$store.state.count
    },
}
Copy the code

I’m going to put it down here

export default class test extends Vue {
   get count() {
    // Vuex state is used
      return this.$store.state.count
   }
  add() {
  // vuexAdd method defined in Vuex achieves +1 function
    this.$store.commit('vuexAdd')}}Copy the code