K
K
Konstantin2019-02-26 07:20:42
Vue.js
Konstantin, 2019-02-26 07:20:42

Vuex, can't get data from store.state?

Good afternoon.
How do I get data from productName if I get Observer
comp.vue

export default {
    data() {
        return {
            productName: this.$store.state.products
        }

store.js
export default {
    state: {
        products: [],
        productName: []
    },
    mutations: {
        LOAD_ALL_PRODUCTS(state, payload) {
            state.products = payload
        }
    },
    actions: {
        async loadAllProducts({commit}) {
            try {
                let res = await Vue.axios.get('/products/')
                commit('LOAD_ALL_PRODUCTS', res.data)
            } catch(err) {
                 console.log(err)
            }
        }
    },
    getters: {
        getProducts: state => state.products,

gives out:
mounted() {
        console.log(this.productName);

5c74be730bae5026802619.png

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Kuznetsov, 2019-02-26
@dima9595

res.data.products and v-for!?

L
Lumore, 2019-02-26
@Lumore

You need to use computed:

<template>
  <div>
    <div v-for="(product, index) in products" :key="index">{{product.name}}</div>
  </div>
</template>

export default {
  computed: {
    products () {
      return this.$store.state.products
    }
  }
}

K
karambafe, 2019-02-26
@karambafe

If you want to subscribe to data from a store, then use computed properties:

export default {
  computed: {
    productName() {
       return this.$store.state.products.map(product => product.name);
    },
  },
};

In the store, you don’t need to have a separate productName state at all, because this is a computed value relative to the products state - you can declare it as a separate productName getter in Vuex, or you can get it via computed in the component as described above
Vuex getters

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question