0

I'm using VUEX GETTERS for some variables. I can use them in the html part but I cannot edit or change them in the script->data part.

ERROR:[Vue warn]: Error in data(): "ReferenceError: Positions is not defined"

<script>
import {mapGetters} from 'vuex'
export default {
        data: () => ({
            dialog: false,
            TotalEntitiy:Positions[0] // GIVES ERROR
        }),       
        computed:{
            ...mapGetters({
                PageTitle:  'GETTER_CURRENT_PAGE',
                headers:   'GETTER_HEADERS',
                Positions: 'GETTER_POSITIONS',
                items:'GETTER_ITEMS'
            }),
0

1 Answer 1

3

Define TotalEntity a new computed property instead of part of the component's data, since it has to be reactive based on the value from the store:

data: () => ({
    dialog: false
}),       
computed:{
    ...mapGetters({
        PageTitle:  'GETTER_CURRENT_PAGE',
        headers:   'GETTER_HEADERS',
        Positions: 'GETTER_POSITIONS',
        items:'GETTER_ITEMS'
    }),
    TotalEntity() {
        return this.Positions[0];
    }
}

Update: to circumvent potential issues that this.Positions might be null or undefined, you can use the optional chaining operator ?.:

return this.Positions?.[0];

You can also use nullish coalescing operator to fallback to a default value:

return this.Positions?.[0] ?? YOUR_FALLBACK_VALUE;
Sign up to request clarification or add additional context in comments.

2 Comments

I think return this.Positions && return this.Positions[0] would be better as this.Positions can be undefined at some point
@VirajSingh Thanks: updated my answer to include handling of null or undefined values

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.