💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
>[success] # pinia -- getter 1. 需要在`store`中定义了`getters`,在使用中常见的几种场景 * 正常第一个`getter` 将其 理解为一个计算属性用来配合`state` * 一个`getter`引入另外一个`getter` * 利用`getters`返回一个函数 * getters中用到别的store中的数据 2. `getters `中定义的函数也可以使用`this`,返回的为当前`store `对象,可以去调用对象中的`state `或者其他`getter`,但使用`this `时候在使用`ts` 会导致`ts `不能自动判断类型 ~~~ export const useStore = defineStore('main', { state: () => ({ counter: 0, }), getters: { // 自动将返回类型推断为数字 doubleCount(state) { return state.counter * 2 }, // 返回类型必须明确设置 doublePlusOne(): number { return this.counter * 2 + 1 }, }, }) ~~~ >[danger] ##### 案例 * store ~~~ import { defineStore } from "pinia"; // 第一个参数是应用程序中 store 的唯一 id export const useCountStore = defineStore("count", { // 其它配置项 state: () => ({ counter: 0, ls: [1, 12, 31, 48, 5], }), getters: { // 自动将返回类型推断为数字 // 箭头函数表现形式 doubleCount: (state) => state.counter * 2, doubleCount(state) { return state.counter * 2; }, // 也可也使用this 访问state doublePlusOne() { console.log(this); return this.counter * 2 + 1; }, // 使用this 访问getter doubleCountPlusOne() { // 自动完成 return this.doubleCount + 1; }, // 函数 getIndexBynunber(state) { return function (cnum) { return state.ls.findIndex((num) => cnum === num); }; }, // 想访问其他store 中的值 只要把其他store 引入即可 import { useOtherStore } from './other-store' // otherGetter(state) { // const otherStore = useOtherStore() // return state.localData + otherStore.data // }, }, }); ~~~ * 视图,使用上直接使用即可不用像`vuex `需要在声明`getter.调用` ~~~html <template> <div> {{ doubleCount }}, {{ doublePlusOne }}, {{ doubleCountPlusOne }}, {{ getIndexBynunber(2) }} </div> </template> <script setup> import { storeToRefs } from "pinia"; import { useCountStore } from "@/store/modules/count"; // 使用创建的 defineStore 创建的 usersStore 函数 const { doubleCount, doublePlusOne, doubleCountPlusOne, getIndexBynunber } = storeToRefs(useCountStore()); </script> ~~~