[Vuejs]-Why won't Vuex getter work in this simple code?

1๐Ÿ‘

โœ…

You have missed it to return it from your computed variable and in your template check for length of product before printing it.

<div v-if="Product.length">
Vue.component('product-info', {
  template: '<div v-if="Product.length"> {{Product[0].ProductTitle}} </div>',
  computed: {
    Product() { return this.$store.getters.getProduct},

  },
  mounted() {
    if (!this.Product.length) {
      this.getProduct();
    }

    // you need to right some promise to get value from length in your `axios`, eg:
    setTimeout(() => { console.log('product length:', this.Product.length)}, 1000)
  },
  methods: {
    getProduct() {
      return this.$store.dispatch('loadProduct')
    }
  }
});

let ProductData = [{
  "ProductID": 101,
  "ProductTypeID": 1,
  "ProductTitle": "Sony PS4 Pro with Death Standing",
  "ProductDescription": "<p>Grab yourself a new console complete with a top title with the Sony PlayStation 4 Pro & Death Stranding Bundle</p>\n  <p>Experience the most spectacular graphics on every game and film with the PlayStation 4 Pro โ€“ with 4K Ultra HD resolution and HDR compatibility.  Twice the power as previous models, the PlayStation 4 Pro achieves faster and more stable frame rates as well as incredibly lifelike details.</p>"
}];

const store = new Vuex.Store({
  state: {
    Product: []
  },
  actions: {
    loadProduct({
      commit
    }) {
      commit('setProduct', ProductData)
    }
  },
  getters: {
    getProduct: (state) => state.Product
  },
  mutations: {
    // you need to write your sxios promise here
    setProduct(state, ProductData) {
      state.Product = ProductData
    }
  }
})

const app = new Vue({
  store,
  el: '#app'
})
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app">
  <product-info></product-info>
</div>

3๐Ÿ‘

You have to declare the computed property as a function:

computed: {

    Product() { return this.$store.getters.getProduct }

}

Leave a comment