日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

pinia的常用知識點(diǎn)及搭配“script setup”的使用

作者:大橘為重¨ 更新時間: 2023-07-14 編程語言

pinia的常用知識點(diǎn)及搭配“script setup”的使用

  • 前言
  • 一、安裝pinia
  • 二、創(chuàng)建一個store
  • 三、Store 間的相互訪問
  • 四、pinia 中常用的內(nèi)置方法
  • 五、pinia的分模塊使用例子
  • 六、補(bǔ)充:composition API 寫法


前言

對比于vuex,新的Vue狀態(tài)管理庫pinia更加的輕量。并且具有更加明顯的優(yōu)勢,包括有:拋棄傳統(tǒng)的 mutation,通過action對同異步進(jìn)行操作簡化狀態(tài)管理庫;不需要嵌套模塊,讓代碼扁平化;更好的TypeScript支持;更友好的調(diào)用方式等。同時結(jié)合vue3.2推出的setup語法糖使用會得到更加友好的體驗(yàn)。

一、安裝pinia

  1. npm 安裝

npm install pinia

  1. main.ts下導(dǎo)入pinia
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'

createApp(App).use(createPinia()).mount('#app')

二、創(chuàng)建一個store

項(xiàng)目結(jié)構(gòu):
在這里插入圖片描述

  • 導(dǎo)入 “defineStore()”
  • 為每個 store 規(guī)定唯一的命名
  • 按需創(chuàng)建 state、getters、actions 部分操作
import { defineStore } from 'pinia'

export const mainStore = defineStore('main', {
    state: () => ({
    	// 在該項(xiàng)中可以自定義狀態(tài)數(shù)據(jù)
        // ......
        sum:0
    }),
    getters: {
    	// 該項(xiàng)等同于 Store 狀態(tài)的 計(jì)算值,類似于計(jì)算屬性
        // ......
        getDoubleSum(state) {
        	return state.sum*2
        }
    }
    actions: {
    	// 相當(dāng)于組件中的 methods,用于定義和處理業(yè)務(wù)邏輯
        //.......
        addSum(value: number) {
        	this.sum += value
		}
    }
})
注:this 可以訪問到自身的 store 實(shí)例
  • Pinia 創(chuàng)建的 Store 動作被派發(fā)為普通的函數(shù)調(diào)用,不再需要使用dispatch 方法或MapAction 輔助函數(shù)
<template>
    <div>
        <p>sum:{{useMainStore.sum}}</p>
        <p>doubleSum:{{useMainStore.getDoubleSum}}</p>
        <button @click="useMainStore.addSum(1)">sum+1</button>
    </div>
</template>

<script setup lang="ts">
import { mainStore } from "../store/index";
const useMainStore = mainStore()

</script>

三、Store 間的相互訪問

  • 調(diào)用對應(yīng)創(chuàng)建的 “Store方法” 即可獲取實(shí)例使用

例如:

import { defineStore } from 'pinia'

export const mainStore = defineStore('main', {
    state: () => ({
        sum: 0,
    }),
})

export const otherStore = defineStore('other', {
    state: () => ({
        doubleSum: 0
    }),
    getters: {
        updateDoubleSum(state) {
        	// 獲取 "mainStore" 的實(shí)例,并使用其中的 sum 狀態(tài)
            const useMainStore = mainStore()
            state.doubleSum = useMainStore.sum * 2
            return state.doubleSum
        }
    }
})

四、pinia 中常用的內(nèi)置方法

  • 重置狀態(tài)到初始值
  • 通過調(diào)用 store 上的 $reset() 方法可將狀態(tài)重置
const store = useStore()
store.$reset()
  • 一次更改多個狀態(tài)
  • 通過調(diào)用 store 上的 $patch 方法,支持使用部分 “state” 對象同時應(yīng)用多個更改
const store = useStore()
store.$patch({
  counter: store.counter + 1,
  name: 'Abalam',
})

五、pinia的分模塊使用例子

項(xiàng)目結(jié)構(gòu):
在這里插入圖片描述

  • index.ts 文件:
import { createPinia } from 'pinia'
import useUserStore from "./modules/user/index";
import useAppStore from "./modules/app/index";

const pinia = createPinia()

export { useUserStore, useAppStore }
export default pinia
  • main.ts 文件:
import { createApp } from 'vue'
import App from './App.vue'
import pinia from "./pinia";

createApp(App).use(pinia).mount('#app')
  • 模塊文件,這里展示 user 模塊:
  • types.ts 文件:
export type RoleType = '' | 'admin' | 'user'

export interface UserState {
    name?: string;
    email?: string;
    phone?: string;
    introduction?: string;
    role: RoleType;
}
  • index.ts 文件:
import { defineStore } from "pinia";
import type { UserState, RoleType } from "./types";
import { getUserInfo } from "@/network/test";

const useUserStore = defineStore('user',{
    state:():UserState=>({
        name: undefined,
        email: undefined,
        phone: undefined,
        introduction: undefined,
        role:''
    }),
    getters:{
        userInfo(state:UserState):UserState {
            return {...state}
        }
    },
    actions:{
        setRole(role: RoleType) {
            this.role = role
        },
        setInfo(partial: Partial<UserState>) {
            this.$patch(partial);
        },
        resetInfo() {
            this.$reset()
        },
        async info() {
            const res:any = await getUserInfo();
            this.setInfo(res.data);
        },
    }
})

export default useUserStore

六、補(bǔ)充:composition API 寫法

上面的store均使用 options API 的寫法,以下我們改為使用 composition API 模式定義store,改寫法更符合Vue3 setup的編程模式,讓結(jié)構(gòu)更加扁平化,寫法轉(zhuǎn)化如下:

  • 使用 ref、reactive 定義的變量代替 options API中的state;
  • 使用 computed 代替 options API中的getters;
  • 直接書寫 函數(shù)代替 options API中的actions;

現(xiàn)在我們使用上面的寫法把“目錄一”創(chuàng)建的store改為 composition API 的寫法:

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const mainStore = defineStore('main', ()=>{
	const sum = ref<number>(0)
	const doubleSum = computed<number>(() => sum.value * 2)
	const addSum = (value: number) => {
		sum.value += value
	}
	
	return { sum, doubleSum, addSum }
})

提示:文章到此結(jié)束,文章僅為個人學(xué)習(xí)記錄,若有不足還請大家指出。

原文鏈接:https://blog.csdn.net/weixin_53068161/article/details/126785114

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新