[Vuejs]-Using nested properties from object in Vuex store inside a template

2πŸ‘

βœ…

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>

Leave a comment