如何针对非类 TypeScript 对象链接函数

问题描述 投票:0回答:1

我在 Pinia 商店中有一些 Vue3(CompositionAPI)代码,但更具体地说,这是一个 TypeScript 问题。

代码如下所示:

export const useCommonStore = defineStore("commmon", () => {

const commonState = reactive({
    isRequestLoading: false,
    lookupsLoaded: false,
    lineOfBusinesses: LookupItem[]
    )};

    
export const emptyOption = {value: 0, name: "No selection"};


const withEmptyOption = (options: Array<ILookupItem>) => {
    return [emptyOption, ...options];}

}

要在其他地方使用它(例如在 Vue 组件中),我的代码如下所示:

commonStore.withAllOption(commonStore.commonState.lineOfBusinesses)

而且我不喜欢它。我宁愿有

commonStore.state.lineOfBusinesses.withAllOptions()

但我不知道该怎么做!有人可以帮我吗?

typescript vuejs3 pinia
1个回答
0
投票

您可以使用

this

从商店内访问该值
interface CommonStoreState {
  isRequestLoading: boolean;
  lookupsLoaded: boolean;
  lineOfBusinesses: LookupItem[];
}
export const useCommonStore = defineStore("commmon", () => {
  state:(): CommonStoreState => ({
    isRequestLoading: false,
    lookupsLoaded: false,
    lineOfBusinesses: [],
  )},
  getters: {},
  actions: {
    withAllOption(): void {
      console.log('lineOfBusinesses', this.lineOfBusinesses);
    },
  }
});

    
export const emptyOption = {value: 0, name: "No selection"};


const withEmptyOption = (options: Array<ILookupItem>) => {
    return [emptyOption, ...options];}

}

其他地方

commonStore.withAllOption();
// Log (commonStore.ts, ln 15)
// > lineOfBuisnesses: [...]
© www.soinside.com 2019 - 2024. All rights reserved.