## pinia的简单使用
npm install pinia --save
## 创建 Store
新建 src/store 目录并在其下面创建 index.ts,导出 store,在 main.ts 中引入并使用
export const useUserStore = defineStore({
id: '',
state: () => {
return {
}
},
getters: {
},
actions: {
}
})
## Pinia 没有 mutations,统一在 actions 中操作 state,通过this.xx 访问相应状态虽然可以直接操作 Store,但还是推荐在 actions 中操作,保证状态不被意外改变,支持多个Store
import { createPinia, defineStore } from 'pinia'
interface State {
text: string,
num: number
}
export const useUserStore = defineStore({
id: 'space',
state: (): State => ({
text: 'yy',
num: 18
}),
getters: {
getText(): string {
return this.text + '????'
}
},
actions: {
addNum(data: any) {
console.log('data :>> ', data)
this.printData()
this.num++
},
printData() {
console.log('打印信息')
}
}
})
export const store = createPinia()
<template>
<div>{{ userStore.text }}</div>
<p>{{ userStore.num }}</p>
<button @click="addNum">发送</button>
</template>
<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/store'
const userStore = useUserStore()
const { num } = storeToRefs(userStore)
const addNum = () => {
userStore.addNum(18)
console.log(userStore.getText)
}
</script>