0

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>

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

6 Comments

This doesn't make any difference from calling '$store.getters['x/y'].prop1'. So your answer is pointless.
I'm asking if I can scope objects to blocks.
@Arrrr the simple answer is no. I updated my answer to reflect that and added another alternative.
I'm not trying to take revenge :D, on the other hand, I really appreciate your help. This is what I had in mind in the first place but if there isn't any better way, have no choice but to stick to it.
@Arrrr Vue makes it really easy to split into components (as small as they can be) and I think we should embrace that ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.