skip to Main Content

I know that Pinia offers some more features, like debugging, which I don’t really need, so I was thinking to use just the composition api for store.

But I noticed in with Pinia you can access values from variables directly.

example- with pinia:

export default defineStore('test', () => {
  const test = computed(() => { ... });
  return { test};
});

without pinia:

export default () => {
  const test = computed(() => { ... });
  return { test };
};

in the first example I can access store.test in my scripts, but in the 2nd example I need to call the value, store.test.value

I understand that computed vars need to be accessed by this value prop in vue, but how come Pinia allows you to ommit it? And is there a way to reproduce this behaviour without Pinia?

2

Answers


  1. I haven’t looked into pinia’s source code, but I’m guessing they do some transformations and don’t just give you back your return value.

    If you want that specific behavior, it’s pretty simple really: just wrap your object in a reactive

    return reactive({
      test,
      /*myRef,
      myShallowRef,
      myComputed,*/
    });
    

    As the docs indicate, reactive does some ref unwrapping

    Login or Signup to reply.
  2. in vue.js, the composition Api allows you to define reactive data using ref and reactive functions. When you use ref you need to access the value using .value because ref wraps the value in an object to make it reactive.

    However, Pinia, being a state management library specifically designed for Vue.js, offers additional feature that simplify the state management. One of these features is the automatic unwrapping of ref values, allowing them directly without using .value.

    Here is how Pinia achieves this behaviour:

    Automatic Unwrapping: Pinia automatically unwraps ref values when accessed, allowing you to use the store property directly without needing to access the .value property:

    Example:

    ```///with Pinia 
    export default defineStore ('test', () => {
    const test = ref ('Hello');
    return {test};
    });
    //Accessing the store property.
    console.log(store.test); //'Hello'
    
    //Without Pinia
    const test = ref ('Hello');
    console.log(test.value); //'Hello'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search