2017-10-14 100 views
0

我需要創建兩個共享數據的組件。我製作添加或刪除指定項目的項目列表和項目購物車。Vue組件數據不會更新

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/

+1

您可能需要使用的事件,而不是讓與項目直接陣列孩子亂嘗試。 – hayavuk

+0

我不明白你 – 50l3r

+0

https://vuejs.org/v2/guide/components.html#Using-v-on-with-Custom-Events – hayavuk

回答