Search code examples
vue.jsvue-componentvuejs2vuex

Data from Vuex storage are not displayed in the vue component


The Vuex storage has a getter which returns object by id. But I can't use the data from the getter.

When i use computed: data come from getter after the component was rendered, and DOM still empty (until I'm not clicking on component in vue devtools. If i click, computed run again, and element are redrawn and filled with the data from data())

if I call the getter directly during the definition of data() objects, {{ cardData.content }} in DOM can be seen immediately, but this.cardData.title returns an error Cannot read property 'title' of undefined. Why?

Vuex storage

export const store = new Vuex.Store({
    state: {
        "cards": [
            {
                "position": null,
                "title": "Head Text",
                "id": 132,
                "content": "LoremIpsum",
                "type": "text",
            },
            {
                "position": null,
                "title": "Head Text 2",
                "id": 138,
                "content": "LoremIpsumLoremIpsum",
                "type": "text",
            }
        ]
    },

    getters: {
        cards: (state) => state.cards
    }
});

vue component,

<template>
<div>
  <h1>{{ cardTitle }}{{ cardTitle2 }}</h1>
  <div>{{ cardData.content }}</div>
</div>
</template>


<script>
  export default {
    props: ['id'],
    data() {
      return {
        cardData: this.$store.getters.cards.find((card) => card.id == this.id),
        cardTitle: this.cardData.title,
        cardData2: null,
        cardTitle2: null
      }
    },
    computed: {
      GetData: function() {
        this.cardData2 = this.$store.getters.cards.find((card) => card.id == this.current);
        this.cardTitle2 = this.cardData2.title;
      },
    } 
  }

</script>

Solution

  • Why not just have a computed property which returns desired title, it can be just following as documented here:

    computed: {
      cardTitle: function() {
       var card = this.$store.getters.cards.find((card) => card.id == this.current)
       return card.title
      },
    } 
    

    Now you can use {{this.cardTitle}} in the DOM.