簡體   English   中英

Vue 組件數據不更新

[英]Vue Component Data doesn't update

我需要創建兩個共享數據的組件。 我制作了添加或刪除指定項目的項目列表和項目購物車。

HTML:

<script>
  var food_menu = '[{"cat":"Burgers","name":"Hamburger classic","text":"200g of meat with chips","price":"9,50"},{"cat":"Burgers","name":"Hamburger chili","text":"250g of meat with chips + drink (orange juice 0,5l)","price":"12,50"},{"cat":"Burgers","name":"Chickenburger","text":"250g of meat with chips + drink (orange juice 0,5l)","price":"10,50"},{"cat":"Burgers","name":"Chickenburger chili","text":"250g of meat with chips + drink (orange juice 0,5l)","price":"14,50"},{"cat":"Steaks","name":"Baconburger","text":"300g of meat with chips","price":"16,50"},{"cat":"Steaks","name":"Hotburger","text":"300g of meat with chips + drink (orange juice 0,5l)","price":"18,50"},{"cat":"Maxs","name":"Hotburger max","text":"450g of meat with chips","price":"21,50"},{"cat":"Maxs","name":"Chickenburger max","text":"450g of meat with chips","price":"15,50"}]';

</script>

<body>
  <main>
      <cart></cart>
      <food :menu="menu"></food>
  </main>
  <script src="https://unpkg.com/vue"></script>
</body>

購物車組件:

const cart = Vue.component('cart', {
  template: `
    <div>
      <pre>{{$data}}</pre>
    </div>
  `,
  data() {
    return {
      items: []
    }
  },
  created() {
    this.$parent.$on("añadir", (item, index) => {
    alert('asdasd')
      if (typeof this.items[index] === "undefined") {
        this.items[index] = item;
        this.items[index].quantity = 1;
      } else {
        this.items[index].quantity++;
      }
    });
  }
});

項目列表組件(有效)

const food = Vue.component('food', {
  props: ['menu'],
  template: `
      <div>
        <div class="food-item" v-bind:class="item.cat" v-for="(item,index) in menu">
          <h3>{{item.name}}</h3>
          <a class="add-cart" v-on:click="addToCart(item, index)">Añadir al carro</a>
          <p>{{item.text}}</p>
          <span>{{item.price}}€</span>
        </div>
    </div>
  `,
  methods: {
    addToCart(item, index) {
      this.$parent.$emit('añadir', item, index);
    }
  }
});

以及分離的實例:

new Vue({
    el: 'main',
    data: {
      menu: JSON.parse(food_menu)
    },
    components: {
      'food': food,
      'cart': cart
    }
  });

當我嘗試修改“項目”時,它不會更改模板。

https://jsfiddle.net/50l3r/wu0gjz2r/6/

我在 vue 論壇上發現問題: https ://forum.vuejs.org/t/vue-component-data-doesnt-update/20086

由於我無法像這樣修改數組而導致的問題:

this.items[index] = newValue
this.items.length = newLength

我需要使用:

Vue.set(this.items, index, newValue)

或者

this.items.push()
this.items.splice()

文檔鏈接: https ://v2.vuejs.org/v2/guide/list.html#Caveats

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM