1.创建一个模块状态并且暴露出去
export default{
namespaced: true, // 模块化 必要
state: {
num: 100,
age: 12
},
getters: {
getNum: state => state.num + 20,
getAge: state => state.age / 2
},
mutations: {
PULS: (state) => {
state.num += 10
},
MITT: (state) => {
state.num -= 10
}
},
actions: {
onMitt: ({commit}) => {
commit('MITT')
}
},
}
2.在store/index.js中引入模块
import { createStore, } from 'vuex'
import sum from '../store/sum'; // 将模块导入
// ......
export default createStore({
// ......
modules: {
sum,
// ......
}
})
3.在组件页面中使用
<template >
<div>
<h1>Setup!!!</h1>
<button @click="onPuls">+10</button>
<button @click="onMitt">-10</button>
<p>steta:{{ num }}</p>
<p>getters:{{ getNum }}</p>
<h1>{{ getAge }}</h1>
</div>
</template>
<script setup>
import {computed} from 'vue';
import {useStore} from 'vuex';
const store = useStore()
// 访问 vuex 中的状态state
const num = computed(() => {return store.state.sum.num })
// 访问 vuex 中的getters函数 '模块名字/函数名字'
const getNum = computed(() => store.getters["sum/getNum"] )
const getAge = computed(() => store.getters["sum/getAge"] )
// 访问 mutations '模块名字/函数名字'
let onPuls = () => { store.commit('sum/PULS') }
// 访问 actions
const onMitt = () => { store.dispatch('sum/onMitt') }
</script>