Assuming that I have a getter for my Vuex.Store
that returns an object with many properties and I want to use this object in a component. Is there any way to do something similar to this:
<div v-bind="$store.getters['x/y']">
<p>{{scopedObject.prop1}}</p>
</div>
instead of:
<div>
<p>{{$store.state.x.data.y.prop1}}</p>
</div>
I'm asking if I can scope objects to blocks.
The simple answer is no.
You could define a computed
property which returns the nested object.
computed: {
scopedObject() {
return this.$store.getters['x/y'];
}
}
In fact, this is where mapGetters
is meant to be used.
import { mapGetters } from 'vuex';
export default {
computed: mapGetters({ scopedObject: 'x/y' }),
}
Then, the template would simply be
<div>
<p>{{scopedObject.prop1}}</p>
</div>
If you really want to make a new scope, define a new component which will only define the section of the template you want it to use.
A simple prop
could be used, so it doesn't need to know about the store.
<template>
<div>
<p>{{scopedObject.prop1}}</p>
</div>
</template>
<script>
export default {
props: {
scopedObject: {
type: Object,
required: true
},
},
};
</script>
Then, in the parent:
<template>
<scoped-component :scoped-object="$store.getters['x/y']"><scoped-component>
</template>