如何在TypeScript中使用Vuex

1,165 阅读1分钟

例如用TypeScript+VueX实现简单的点击实现加1功能

1.写入state和mutations /src/store/index.js文件代码如下

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

Vue.use(Vuex) // 把store 绑到 Vue.prototype
export default new Vuex.Store({
  // 相当于vue中的data
  state: {
    count: 0,
  },
  //相当于vue中的methods
  mutations: {
    vuexAdd(state) {
      state.count ++
    },
  },
})

2.于main.ts中加载store文件夹

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


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

3.于test.vue中使用

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

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

@Component({
  computed: {
  //我们在使用Vuex中的数据,最好定义在computed计算属性中,这样变动可以即时更新
    count() {
    //使用了Vuex的state
      return this.$store.state.count
    },
  },
})
export default class test extends Vue {
  add() {
  // 使用了Vuex的mutations中定义的vuexAdd方法实现+1功能
    this.$store.commit('vuexAdd')
  }
	
}

点击后:

上面出现了一个问题,这在computed里拿出来的Vuex数据只能在template摸板中使用,在下方script里面使用就会报错,查阅文档半个小时后在Vue Class Component找到解决办法,就是利用ES6的get方法

所以我们的


 computed: {
  //我们在使用Vuex中的数据,最好定义在computed计算属性中,这样变动可以即时更新
    count() {
    //使用了Vuex的state
      return this.$store.state.count
    },
}

要放到下面中,变成

export default class test extends Vue {
   get count() {
    //使用了Vuex的state
      return this.$store.state.count
   }
  add() {
  // 使用了Vuex的mutations中定义的vuexAdd方法实现+1功能
    this.$store.commit('vuexAdd')
  }
	
}