Pinia学习笔记之--核心概念Getters

18 篇文章 5 订阅

Getters

getterStore状态的计算值完全相同。它们可以用defineStore()中的getters属性来定义。它们接收state作为第一个参数,以鼓励使用箭头函数:

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

大多数时候,getter只依赖于状态,但是,它们可能需要使用其他getter。因此,当定义一个常规函数时,我们可以通过这个函数访问整个store实例,但需要定义返回的类型(在TypeScript中)。这是由于TypeScript中的一个已知限制,不会影响用箭头函数定义的getter,也不会影响不使用Thisgetter:

export const useStore = defineStore('mian', {
    state: (() => {
        counter: 0
    }),
    getters: {
        // 自动推断类型为nubmer
        doubleCount(state) {
            return state.counter * 2
        },
        // 返回的类型必须被设置
        doublePlusOne(): number {
            // autocompletion and typings for the whole store
            return this.doubleCount + 1
        }
    }
})

然后你可以直接访问store实例getter

<template>
    <p>Double count is {{ store.doubleCount }}</p>
</tempalte>
<script>
    export default {
        setup() {
            const store = useStore()
            return { store }
        }
    }
</script>

访问其它的getters

与计算属性一样,您可以组合多个getters。通过this访问任何其他的getters。即使您不使用TypeScript,您也可以使用JSDoc提示IDE输入的类型

export const useStore = defineStore('main', {
  state: () => ({
    counter: 0,
  }),
  getters: {
    // type is automatically inferred because we are not using `this`
    doubleCount: (state) => state.counter * 2,
    // here we need to add the type ourselves (using JSDoc in JS). We can also
    // use this to document the getter
    /**
     * Returns the counter value times two plus one.
     *
     * @returns {number}
     */
    doubleCountPlusOne() {
      // autocompletion ✨
      return this.doubleCount + 1
    },
  },
})

给getters传参数

Getter只是后台的计算属性,所以不可能向它们传递任何参数。但是,你可以从getter返回一个函数来接受任何参数:

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

然后再组件中这样使用:

<script>
export default {
    setup() {
        const store = useStore()

        return {
            getUserById: store.getUserById
        }
    }
}
</script>
<template>
  <p>User 2: {{ getUserById(2) }}</p>
</template>

注意,当这样做时,getter不再被缓存,它们只是您调用的函数。然而,你可以在getter本身中缓存一些结果,这是不常见的,但更高效:

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

访问其它实例的getters

要使用另一个store中的 getter,你可以直接在getter中使用它:

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

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

在setup()中的用法

你可以直接访问任何getter作为存储的属性(完全像state属性):

export default {
  setup() {
    const store = useStore()

    store.counter = 3
    store.doubleCount // 6
  },
}

Options API 中的用法

对于以下示例,您可以假设创建了以下store:

// Example File Path:
// ./src/stores/counterStore.js

import { defineStore } from 'pinia',

const useCounterStore = defineStore('counterStore', {
  state: () => ({
    counter: 0
  }),
  getters: {
    doubleCounter() {
      return this.counter * 2
    }
  }
})

使用 setup()

虽然Composition API并不适合所有人,但是setup()钩子可以让Pinia更容易在Options API中使用。不需要额外的帮助函数!

import { useCounterStore } from '../stores/counterStore'

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

    return { counterStore }
  },
  computed: {
    quadrupleCounter() {
      return counterStore.doubleCounter * 2
    },
  },
}

不使用 setup()

你可以使用在前一节中使用的mapState()函数来映射到getter:

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

export default {
  computed: {
    // gives access to this.doubleCounter inside the component
    // same as reading from store.doubleCounter
    ...mapState(useCounterStore, ['doubleCount'])
    // same as above but registers it as this.myOwnName
    ...mapState(useCounterStore, {
      myOwnName: 'doubleCounter',
      // you can also write a function that gets access to the store
      double: store => store.doubleCount,
    }),
  },
}
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Pinia 是一个用于 Vue.js 的状态管理库,它提供了一种简单且可扩展的方式来管理应用程序的状态。Pinia-plugin-persistedstate 是一个 Pinia 插件,它可以帮助你将应用程序的状态持久化到本地存储中,以便在刷新页面或重新加载应用程序时保持状态的一致性。 使用 pinia-plugin-persistedstate 插件进行持久化的步骤如下: 1. 安装插件: 你可以使用 npm 或者 yarn 来安装插件: ``` npm install pinia-plugin-persistedstate ``` 或者 ``` yarn add pinia-plugin-persistedstate ``` 2. 导入插件并注册: 在你的应用程序的入口文件中,导入 `pinia-plugin-persistedstate` 并将其注册到 Pinia 实例中: ```javascript import { createApp } from 'vue' import { createPinia } from 'pinia' import { createPersistedState } from 'pinia-plugin-persistedstate' const pinia = createPinia() pinia.use(createPersistedState()) const app = createApp(App) app.use(pinia) app.mount('#app') ``` 3. 配置插件: 你可以通过传递选项对象来配置插件,例如指定要持久化的状态模块、存储键名等: ```javascript pinia.use(createPersistedState({ key: 'my-app-state', // 存储键名,默认为 'pinia-state' paths: ['counter'], // 要持久化的状态模块,默认为全部模块 storage: localStorage // 存储引擎,默认为 localStorage })) ``` 4. 使用持久化的状态: 在你的组件中,你可以像使用普通的 Pinia 状态一样使用持久化的状态: ```javascript import { useStore } from 'pinia' export default { setup() { const store = useStore() // 读取持久化的状态 console.log(store.counter) // 修改持久化的状态 store.counter++ } } ``` 这样,你就可以使用 pinia-plugin-persistedstate 插件来实现 Pinia 状态的持久化了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

绝对零度HCL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值