vue3.0 vueX 替代方案pinia的简单使用
vue3.0 vueX 替代方案Pinia的简单使用
-
安装Pinia
yarn add pinia
-
创建
store
文件夹(store
下建立index.ts
)
/*
* @Author: boyyang
* @Date: 2022-01-04 10:38:08
* @LastEditTime: 2022-01-04 10:45:08
* @LastEditors: boyyang
* @Description: pinia
* @FilePath: \boyyang\src\store\index.ts
*/
import type { App } from 'vue'
import { createPinia } from 'pinia'
const store = createPinia()
const setupStore = (app: App<Element>) => {
app.use(store)
}
export {
setupStore,
store
}
- 在
main.ts
文件中使用
/*
* @Author: boyyang
* @Date: 2022-01-01 23:23:55
* @LastEditTime: 2022-01-04 10:49:32
* @LastEditors: boyyang
* @Description: 项目入口文件
* @FilePath: \boyyang\src\main.ts
*/
import App from './App.vue'
import { createApp } from 'vue'
import { setupRouter, router } from './router'
import { setupStore } from '@/store'
const bootstrap = async () => {
const app = createApp(App)
// 挂载store
setupStore(app)
// 挂载路由
setupRouter(app)
// 路由挂载完毕
await router.isReady()
app.mount('#app')
}
void bootstrap()
- 在
store
文件下创建moudules
文件夹在moudules
文件下添加文件user.ts
以下是user.ts
文件内容
/*
* @Author: boyyang
* @Date: 2022-01-04 11:03:52
* @LastEditTime: 2022-01-04 11:15:49
* @LastEditors: boyyang
* @Description: 用户信息
* @FilePath: \boyyang\src\store\modules\user.ts
*/
import { defineStore } from 'pinia'
import { store } from '@/store'
export interface IUserState {
token: string
}
const useUserStore = defineStore({
id: 'app-user',
state: (): IUserState => ({
token: 'user-token'
}),
getters: {
getToken(): string {
return this.token
}
},
actions: {
setToken(token: string) {
this.token = token
}
}
})
const useUserStoreWithOut = () => {
return useUserStore(store)
}
export {
useUserStore,
useUserStoreWithOut
}
- 在
setup
中使用
<script lang="ts" setup>
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
let token: string = userStore.getToken
</script>
- 在非
setup
中使用如xxx.ts
import { useUserStoreWithOut } from '@/store/modules/user'
const userStore = useUserStoreWithOut()
const token: string = userStore.getToken