美文网首页
vue2值被更新,视图没有变化

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

作者: 柯柯的呵呵哒 | 来源:发表于2024-08-07 17:23 被阅读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()

相关文章

网友评论

      本文标题:vue2值被更新,视图没有变化

      本文链接:https://www.haomeiwen.com/subject/zwfckjtx.html