npm install vuex@next --save
在src
文件下新建store -> index.ts
文件,store -> appStore
下新建state.ts
厨喂,getters.ts
和措,actions.ts
,mutations.ts
蜕煌,index.ts
文件
-store -> appStore -> index.ts
引入各個(gè)模塊
import state from './state'
import actions from './actions'
import mutations from './mutations'
import getters from './getters'
const appStore = {
state,
mutations,
actions,
getters,
}
export default appStore;
-store -> appStore -> state.ts
export default {
countVuex: 0,
}
-store -> appStore -> getters.ts
export default{
countVuex: (state: any) => state.countVuex
}
-store -> appStore -> actions.ts
export default {
ADD_ACOUNTVUEX(store: any, countVuex: Number) {
store.commit('ADD_ACOUNTVUEX', countVuex)
}
}
-store -> appStore -> mutations.ts
export default {
ADD_ACOUNTVUEX(state: any, countVuex: Number) {
state.countVuex = countVuex
}
}
-
store -> index.ts
文件 創(chuàng)建store
import { createStore } from 'vuex';
import appStore from "./appStore"
export default createStore({
modules: {
appStore
}
})
組件中使用:js
中用const store = useStore();
引入派阱;template
中用$store.state.xxx
引入
<script lang="ts">
import { defineComponent } from "vue";
import { useStore } from 'vuex';
export default defineComponent({
name: 'Hello',
setup() {
const store = useStore();
const addAcountVuex = () => {
console.log("store", store.state)
store.commit('ADD_ACOUNTVUEX', store.state.appStore.countVuex + 1);
}
return {
addAcountVuex,
$store: store
};
},
});
</script>
<template>
<div class="hello-wrap">
<button type="button" @click="addAcountVuex">count is: {{ $store.state.appStore.countVuex }}</button>
</div>
</template>
打包時(shí)候Cannot find name '$store'.
package.json改build打包命令"build": "vite build"
后 npm run build