Vue组件数据不会更新

时间:2017-10-14 12:53:56

标签: javascript ecmascript-6 vuejs2

我需要创建两个共享数据的组件。我制作了添加或删除指定项目的项目列表和项目购物车。

HTML:

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);
    }
  }
});

项目列表组件(It Works)

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

分离的实例:

TagLib.File f = TagLib.File.Create(@"C:\Users\spunit\Desktop\denna.mp3");
TagLib.Id3v2.Tag t = (TagLib.Id3v2.Tag)f.GetTag(TagTypes.Id3v2);
PrivateFrame p = PrivateFrame.Get(t, "albumtype", true);
p.PrivateData = System.Text.Encoding.Unicode.GetBytes("TAG CHANGED");
f.Tag.Album = "test";
f.Save();

当我尝试修改“项目”时,它不会更改模板。

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

1 个答案:

答案 0 :(得分:0)

我发现问题在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://vuejs.org/v2/guide/list.html#Caveats

相关问题