vue3.0 vueX 替代方案pinia的簡單使用


vue3.0 vueX 替代方案Pinia的簡單使用

  1. 安裝Pinia

    yarn add pinia

  2. 創建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
}
  1. 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()
  1. 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
}

  1. setup中使用
<script lang="ts" setup>
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
let token: string = userStore.getToken
</script>
  1. 在非setup中使用如xxx.ts
import { useUserStoreWithOut } from '@/store/modules/user'

const userStore = useUserStoreWithOut()
const token: string = userStore.getToken


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM