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' ?
},
};
CodePudding user response:
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.
// 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>
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.
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
CodePudding user response:
This is called Object Destructring. If a module is returning multiple objects ie {foo, goo, loo} and you want to pick just one foo. you can use return {foo}. But if the module is returning only one object foo, you can use return foo. https://www.javascripttutorial.net/es6/javascript-object-destructuring/