How to conditionally destructure an object property from a Pinia getter?
P粉148434742
P粉148434742 2023-11-08 17:47:18
0
1
759

I have the following stores:

export const useMyStore = defineStore('myStore', {
  state: () => {
    return {
      openTransOnly: false,
      keyword: '',
      openTransStatus: { nextPage: 0, complete: false },
      pastDueTransStatus: { nextPage: 0, complete: false },
    };
  },

  getters: {
    transStatus(state) {
      return state.openTransOnly ? state.openTransStatus : state.pastDueTransStatus;
    },
  },
});

Now let's say I want to convert the "keyword" attribute above into a Ref. This is what I did:

const myStore = useMyStore();
const { keyword: needle } = storeToRefs(myStore);

I also have the following computed properties in my component:

const page = computed({
  get: () => myStore.transStatus.nextPage,
  set: (value) => (myStore.transStatus.nextPage = value),
});

good results. However, I would like to know how to define "pages" using the same "storeToRefs" above. I tried this:

const { keyword: needle, transStatus: { nextPage: page } } = storeToRefs(myStore);

But it says "Page is not defined". What did I do wrong? is it possible?

P粉148434742
P粉148434742

reply all(1)
P粉394812277

As the storeToRefs name suggests, it returns a reference. transStatus is a reference and has no nextPage attribute, it is transStatus.value.nextPage. Due to the way transStatus works and the fact that the value is a scalar, premature destructuring of nextPage can result in a loss of reactivity.

If this is a common usage scenario, the store can incorporate page calculations. Since the store state should not change outside the store, page can be used in conjunction with the setPage action.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template