gpt4 book ai didi

javascript - Vue 组件数据不更新

转载 作者:行者123 更新时间:2023-11-30 21:05:00 25 4
gpt4 key购买 nike

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

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

关于javascript - Vue 组件数据不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46744801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com