99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

Pinia Getter

2023-09-28 14:31 更新

Getter 完全等同于 store 的 state 的計(jì)算值??梢酝ㄟ^(guò) defineStore() 中的 getters 屬性來(lái)定義它們。推薦使用箭頭函數(shù),并且它將接收 state 作為第一個(gè)參數(shù):

export const useStore = defineStore('main', {
  state: () => ({
    count: 0,
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
})

大多數(shù)時(shí)候,getter 僅依賴 state,不過(guò),有時(shí)它們也可能會(huì)使用其他 getter。因此,即使在使用常規(guī)函數(shù)定義 getter 時(shí),我們也可以通過(guò) this 訪問(wèn)到整個(gè) store 實(shí)例,但(在 TypeScript 中)必須定義返回類型。這是為了避免 TypeScript 的已知缺陷,不過(guò)這不影響用箭頭函數(shù)定義的 getter,也不會(huì)影響不使用 this 的 getter。

export const useStore = defineStore('main', {
  state: () => ({
    count: 0,
  }),
  getters: {
    // 自動(dòng)推斷出返回類型是一個(gè) number
    doubleCount(state) {
      return state.count * 2
    },
    // 返回類型**必須**明確設(shè)置
    doublePlusOne(): number {
      // 整個(gè) store 的 自動(dòng)補(bǔ)全和類型標(biāo)注 ?
      return this.doubleCount + 1
    },
  },
})

然后你可以直接訪問(wèn) store 實(shí)例上的 getter 了:

<script setup>
import { useCounterStore } from './counterStore'
const store = useCounterStore()
</script>
<template>
  <p>Double count is {{ store.doubleCount }}</p>
</template>

訪問(wèn)其他 getter

與計(jì)算屬性一樣,你也可以組合多個(gè) getter。通過(guò) this,你可以訪問(wèn)到其他任何 getter。即使你沒(méi)有使用 TypeScript,你也可以用 JSDoc 來(lái)讓你的 IDE 提示類型。

export const useStore = defineStore('main', {
  state: () => ({
    count: 0,
  }),
  getters: {
    // 類型是自動(dòng)推斷出來(lái)的,因?yàn)槲覀儧](méi)有使用 `this`
    doubleCount: (state) => state.count * 2,
    // 這里我們需要自己添加類型(在 JS 中使用 JSDoc)
    // 可以用 this 來(lái)引用 getter
    /**
     * 返回 count 的值乘以 2 加 1
     *
     * @returns {number}
     */
    doubleCountPlusOne() {
      // 自動(dòng)補(bǔ)全 ?
      return this.doubleCount + 1
    },
  },
})

向 getter 傳遞參數(shù)

Getter 只是幕后的計(jì)算屬性,所以不可以向它們傳遞任何參數(shù)。不過(guò),你可以從 getter 返回一個(gè)函數(shù),該函數(shù)可以接受任意參數(shù):

export const useStore = defineStore('main', {
  getters: {
    getUserById: (state) => {
      return (userId) => state.users.find((user) => user.id === userId)
    },
  },
})

并在組件中使用:

<script setup>
import { useUserListStore } from './store'
const userList = useUserListStore()
const { getUserById } = storeToRefs(userList)
// 請(qǐng)注意,你需要使用 `getUserById.value` 來(lái)訪問(wèn)
// <script setup> 中的函數(shù)
</script>


<template>
  <p>User 2: {{ getUserById(2) }}</p>
</template>

請(qǐng)注意,當(dāng)你這樣做時(shí),getter 將不再被緩存,它們只是一個(gè)被你調(diào)用的函數(shù)。不過(guò),你可以在 getter 本身中緩存一些結(jié)果,雖然這種做法并不常見(jiàn),但有證明表明它的性能會(huì)更好:

export const useStore = defineStore('main', {
  getters: {
    getActiveUserById(state) {
      const activeUsers = state.users.filter((user) => user.active)
      return (userId) => activeUsers.find((user) => user.id === userId)
    },
  },
})

訪問(wèn)其他 store 的 getter %{#accessing-other-stores-getters}%

想要使用另一個(gè) store 的 getter 的話,那就直接在 getter 內(nèi)使用就好:

import { useOtherStore } from './other-store'


export const useStore = defineStore('main', {
  state: () => ({
    // ...
  }),
  getters: {
    otherGetter(state) {
      const otherStore = useOtherStore()
      return state.localData + otherStore.data
    },
  },
})

使用 setup() 時(shí)的用法 %{#usage-with-setup}%

作為 store 的一個(gè)屬性,你可以直接訪問(wèn)任何 getter(與 state 屬性完全一樣):

<script setup>
const store = useCounterStore()
store.count = 3
store.doubleCount // 6
</script>

使用選項(xiàng)式 API 的用法 %{#usage-with-the-options-api}%

在下面的例子中,你可以假設(shè)相關(guān)的 store 已經(jīng)創(chuàng)建了:

// 示例文件路徑:
// ./src/stores/counter.js


import { defineStore } from 'pinia'


export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  getters: {
    doubleCount(state) {
      return state.count * 2
    },
  },
})

使用 setup()

雖然并不是每個(gè)開(kāi)發(fā)者都會(huì)使用組合式 API,但 setup() 鉤子依舊可以使 Pinia 在選項(xiàng)式 API 中更易用。并且不需要額外的映射輔助函數(shù)!

<script>
import { useCounterStore } from '../stores/counter'


export default defineComponent({
  setup() {
    const counterStore = useCounterStore()


    return { counterStore }
  },
  computed: {
    quadrupleCounter() {
      return this.counterStore.doubleCount * 2
    },
  },
})
</script>

這在將組件從選項(xiàng)式 API 遷移到組合式 API 時(shí)很有用,但應(yīng)該只是一個(gè)遷移步驟,始終盡量不要在同一組件中混合兩種 API 樣式。

不使用 setup()

你可以使用前一節(jié)的 state 中的 mapState() 函數(shù)來(lái)將其映射為 getters:

import { mapState } from 'pinia'
import { useCounterStore } from '../stores/counter'


export default {
  computed: {
    // 允許在組件中訪問(wèn) this.doubleCount
    // 與從 store.doubleCount 中讀取的相同
    ...mapState(useCounterStore, ['doubleCount']),
    // 與上述相同,但將其注冊(cè)為 this.myOwnName
    ...mapState(useCounterStore, {
      myOwnName: 'doubleCount',
      // 你也可以寫(xiě)一個(gè)函數(shù)來(lái)獲得對(duì) store 的訪問(wèn)權(quán)
      double: store => store.doubleCount,
    }),
  },
}
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)