下载安装

npm install vuex@next --save

yarn add vuex@next --save

全局配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// ------------- store.js ---------------------
import { createStore } from 'vuex'
const store = createStore({
state () {
return{
count: 0
}
},
mutations: {
addCount ( state, num ){
state.count += num
}
},
getters: {
getCount: state => `the state's count is ${state.count}`
}
})
export {store}

// ---------------- main.js --------------
import { createApp } from "vue";
import App from "./App.vue";

import {router} from './router.js'
import {store} from './store.js'

createApp(App).use(router).use(store).mount("#app");

在组合式API中使用Vuex

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<template>
<div>{{showCount}}</div>
<button @click="addCount">+</button>
</template>

<script>
import { reactive, toRefs } from "vue";
import { useStore } from 'vuex'
export default {
setup() {
const store = useStore()
const myCount = reactive({
showCount : store.getters.getCount
})
function addCount(){
store.commit('addCount', 2)
myCount.showCount = store.getters.getCount
}
return {
...toRefs(myCount),
addCount
};
},
};
</script>