前面完成了路由的基本的配置工作,现在进行项目的状态管理的配置,这里使用到的是 pinia
工具
安装
npm install pinia
使用
store / index.ts
import { createPinia } from 'pinia' const pinia = createPinia() export default pinia
简单使用
store / counter.ts
import { defineStore } from 'pinia' const useCounterStore = defineStore('counter', { state: () => ({ counter: 100 }), getters: { double(state) { return state.counter * 2 } }, actions: { changeCounterAction(newNum: number) { this.counter = newNum } } }) export default useCounterStore
Main.vue
<script setup lang="ts"> import useCounterStore from '@/store/counter' const counterStore = useCounterStore() const changeCounter = () => { counterStore.changeCounterAction(15) } </script> <template> {{ counterStore.counter }}-{{ counterStore.double }} <button @click="changeCounter">改变</button> </template> <style scoped></style>