1. 更新
1.1 理解数组改变的检测
1.2 理解更新问题
1.2.1 数组某个位置的值单独做变更
如果你想改变这种行为,需要使用Vue.set(当然需要先import Vue from "vue";):
<template>
<div class="container-fluid">
<h2 class="bg-primary text-white text-center p-3">Products</h2>
<table class="table table-sm table-bordered text-left">
<tr><th>Index</th><th>Name</th><th>Price</th></tr>
<tbody>
<tr v-for="(p, i) in products" v-bind:key="p.name" v-bind:odd="i % 2 == 0">
<td>{{ i + 1 }}</td>
<td>{{ p.name }}</td>
<td>{{ p.price | currency }}</td>
</tr>
</tbody>
</table>
<div class="text-center"><button v-on:click="handleClick" class="btn btn-primary">Press Me</button></div>
<p>
<div class="text-center"><button v-on:click="handleClick2" class="btn btn-primary">Press Me 2</button></div>
</div>
</template>
<script>
import Vue from "vue";
export default {
name: "MyComponent",
data: function () {
return {
products: [
{ name: "Kayak", price: 275 },
{ name: "Lifejacket", price: 48.95 },
{ name: "Soccer Ball", price: 19.50 },
{ name: "Corner Flags", price: 39.95 },
{ name: "Stadium", price: 79500 },
{ name: "Thinking Cap", price: 16 }
]
}
},
filters: {currency(value) {return new Intl.NumberFormat("en-US",{ style: "currency", currency: "USD", }).format(value);
},
},
methods: {
handleClick() {
//this.products.push(this.products.shift());
//如果只是this.products.filter(p => p.price > 20);,是起不到替换作用的,它只是生成了一个新的数组而已
//this.products = this.products.filter(p => p.price > 20);
Vue.set(this.products, 1, { name: "Running Shoes", price: 100 });
},
handleClick2() {this.$set(this.products, 1, { name: "Running Shoes", price: 999 });}
}
}
</script>
<style>
[odd] { background-color: coral; }
</style>