1. 程式人生 > 其它 >Vue3和Vue2使用Vuex的區別(使用ts獲取更佳體驗)

Vue3和Vue2使用Vuex的區別(使用ts獲取更佳體驗)

技術標籤:Webvuejsvuextypescriptvue3

兩者核心區別就是型別提示,像定義元件需要 defineComponent 同出一轍:

Vue3

import { createStore } from "vuex";

import example from './modules/example'

export default createStore({
  state: {},
  mutations: {},
  actions: {},
  modules: { example }
})

Vue2

import Vue from "vue"
; import Vuex from "vuex"; Vue.use(Vuex); export default new Vuex.Store({ state: {}, mutations: {}, actions: {}, modules: {} });

我們以 JavaScript 開發為前提,通過如上對比我們發現為了獲取型別提示 Vuex 提供了 createStore() 函式,相當於原來的 Vuex 例項化過程,與 Vue 3 的函式 application 思想一致。

除此之外,modules 寫法沒有任何變化,在 modules 中,仍需要沿襲以前 Vue 2 的直接匯出方法:

// src/store/modules/example/index.js

export default {
    state,
    mutations,
    actions,
    // 模組化必須,從而形成 dispath('namespace/action') 作用域
    namespaced: true
}

這就導致了在單個 module 中我們不能獲取型別提示,相對乏力,可以考慮使用 TypeScript 改進程式碼提示問題:

export default {
    state,
    mutations,
    actions,
    namespaced: true
}
as Module<object, any>

效果: