009 Vue数组更新专题

1. 更新

1.1 理解数组改变的检测

image.png

1.2 理解更新问题

1.2.1 数组某个位置的值单独做变更

image.png

如果你想改变这种行为,需要使用Vue.set(当然需要先import Vue from "vue";):
image.png
<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>

1.2.2 数组长度发生变化

当通过length缩小数组长度,Vue也不能检测出来这种变化。如果想让Vue发现长度变小,则可以使用splice方法去remove unwanted elements:
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。