1.安装支持 Vue3 的状态管理工具 vuex@next
~~~text
npm i vuex@next
~~~
2.创建`src/store/index.ts`文件
在`src`下创建`store`目录,然后在`store`目录里新建`index.ts`文件:
~~~text
import { createStore } from 'vuex'
const defaultState = {
count: 0
}
// Create a new store instance.
export default createStore({
state() {
return defaultState
},
mutations: {
increment(state: typeof defaultState) {
state.count++
}
},
actions: {
increment(context) {
context.commit('increment')
}
},
getters: {
double(state: typeof defaultState) {
return 2 * state.count
}
}
})
~~~
3.在`main.ts`文件中挂载 Vuex 配置
~~~text
import { createApp } from 'vue'
import App from './App.vue'
import store from './store/index'
createApp(App).use(store).mount('#app')
~~~