源代码如下:问题在于v-model 绑定的是对象,采用的是引用赋值。
<template>
<div class=”hello”>
<h1>购物车练习</h1>
<hr/>
<table>
<tr>
<td>名称:<input type=”text” v-model=”addProductList.name“></td>
<td>价格:<input type=”text” v-model=”addProductList.price”></td>
<td><button @click=”addProduct”>添加商品</button></td>
</tr>
</table>
<hr/>
<table>
<tr>
<td>名称</td>
<td>价格</td>
</tr>
<tr v-for=”(item,index) in ProductList” :key=”index”>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data () {
return {
addProductList: {
name: ”,
price: 0
},
ProductList: [
{
id: 0,
name: ‘物品111’,
price: 998
},
{
id: 1,
name: ‘物品222’,
price: 1998
}
]
}
},
methods: {
addProduct () {
this.ProductList.push(this.addProductList)
// this.addProductList.name = ”
// this.addProductList
}
}
}
</script>
改成如下代码。解决问题
<template>
<div class=”hello”>
<h1>购物车练习</h1>
<hr/>
<table>
<tr>
<td>名称:<input type=”text” v-model=”name”></td>
<td>价格:<input type=”text” v-model=”price”></td>
<td><button @click=”addProduct”>添加商品</button></td>
</tr>
</table>
<hr/>
<table>
<tr>
<td>名称</td>
<td>价格</td>
</tr>
<tr v-for=”(item,index) in ProductList” :key=”index”>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
</tr>
</table>
</div>
</template>
<script>
export default {
data () {
return {
name: ”,
price: 0,
ProductList: [
{
id: 0,
name: ‘物品111’,
price: 998
},
{
id: 1,
name: ‘物品222’,
price: 1998
}
]
}
},
methods: {
addProduct () {
this.ProductList.push(this.addProductList)
// this.addProductList.name = ”
// this.addProductList
}
}
}
</script>
<style scoped>
</style>