Почему Vuex getter не работает в этом простом коде? - PullRequest
0 голосов
/ 24 марта 2020

Я пытаюсь создать JSFiddle, чтобы я мог поэкспериментировать с проблемой, с которой я сталкиваюсь в своем реальном приложении, а затем, надеюсь, показать этот JSFiddle другим. Код приведен ниже, и я получаю сообщение об ошибке

[Vue warn]: Ошибка в смонтированном хуке: «Ошибка типа: Невозможно прочитать свойство« длина »из неопределенного» * ​​1004 *

что я делаю не так?

Vue.component('product-info', {
  template: '<div> {{Product[0].ProductTitle}} </div>',
  computed: {

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

  },
  mounted() {
    if (!this.Product.length) {
      this.getProduct();
    }
  },
  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: {
    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>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
  <product-info></product-info>
</div>

Ответы [ 2 ]

3 голосов
/ 24 марта 2020

Вы должны объявить вычисляемое свойство как функцию:

computed: {

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

}
1 голос
/ 24 марта 2020

Вы пропустили его до return из вычисленной переменной и в template проверке на length продукта перед его печатью.

<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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...