vue2值被更新,视图没有变化

2024-08-07  本文已影响0人  柯柯的呵呵哒

vue2的数据绑定是基于 Object.defineProperty 有的时候,会出现数据更新视图无法更新的情况。例如:

<template>
    <div class="contariner">
        <h1>{{ form.age || '暂无内容'}}</h1>
        <a-button type="primary" @click="change">更改age的值</a-button>
    </div>
</template>

<script>
export default {
    data() {
        return {
            form: {
                name: '柯柯'
            }
        }
    },
    
    methods: {
        change () {
            this.form.age = Math.floor(Math.random()*100)
            console.log(this.form, this.form.age, );
        }
    }
}
</script>

解决方法:
1、使用官方提出的this.$set

this.$set(需要改变的对象,"需要改变的对象属性","新值")

this.$set(this.form, 'age', Math.floor(Math.random()*100))

2、强制更新数据

this.$forceUpdate()

上一篇 下一篇

猜你喜欢

热点阅读