Pinia
安装
npm install pinia
创建 Store
在 src/store 中创建 index.ts,并导出 store
src/store/index.tstypescript
import { createPinia } from 'pinia'
const store = createPinia()
export default store
在 main.ts 中引入并使用
main.tstypescript
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
const app = createApp(App)
app.use(store)
创建 modules
在 src/store 目录下创建 modules 目录,里面存放项目中所需要使用到的状态。演示代码如下
store/modules/user.tstypescript
import { defineStore } from 'pinia'
interface UserState {
name: string
}
export const useUserStore = defineStore({
id: 'user',
state: (): UserState => {
return {
name: 'kuizuo',
}
},
getters: {
getName(): string {
return this.name
},
},
actions: {
setName(name: string) {
this.name = name
},
},
})
使用
获取 state
<template>
<div>{{ userStore.name }}</div>
</template>
<script lang="ts" setup>
import { useUserStore } from '/@/store/modules/user'
const userStore = useUserStore()
</script>