Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pinia 'return {myStore}' vs 'return myStore'

I want to use a Pinia store in a component of my Vue app and I can’t figure out why the store has to be returned in { }? What is the difference between return {foo} vs return foo?

import { usePiniaStore } from "../stores/mainStore";

export default {

  setup() {
    const piniaStore = usePiniaStore();

    return { piniaStore }; //  why isn't it 'return piniaStore' ?
  },
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is really not about Pinia but about what Vue expects as a return value from setup() function. It expects an object. If you try to return something else, Vue gives you an error.

Reason for this is that Vue needs to iterate the properties of returned object (so it knows both the value and it’s name) and create properties with same names on component instance (so they are accessible in template). This is important.

// this will give you an error "setup() should return an object. Received: number"
<script>
  import { defineComponent } from 'vue'
  
  export default defineComponent({
    setup() {
      let myVariable = 10
      
      return myVariable
    }
  })
</script>

The code from your example:

return { piniaStore }

is actually same as:


// creating new JS object 
const returnObject = {
  // first is property name
  // second is property value (from existing variable)
  piniaStore: piniaStore
}

return returnObject

…and it is a valid code from Vue’s point of view

Important thing to remember is that only properties of the returned object are accessible from the template

// you can do this BUT only inner properties of the "myObject" will be accessible in the template
<script>
  import { defineComponent } from 'vue'
  
  export default defineComponent({
    setup() {
      let myObject = {
        variableA: 10,
        variableB: "some string"
      }
      
      return myObject
    }
  })
</script>

Using <div v-if="variableA"> will work. Using <div v-if="myObject"> will not.

Pinia stores are actually objects so returning them directly from setup (without wrapping them in another object) is probably legal and will work. But all above still applies. Your template has no access to piniaStore only to properties (state or getters) and functions (actions) defined on that piniaStore store

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading