数据更新了页面没渲染的解决小方法,不用$set

458 阅读1分钟

vue中对象如果在data里已定义的,它会实时更新,没定义的它不会实时更新;数组它只会更新长度

demo

  • 在数据标签套一层占位标签,用v-if判断渲染
  • 当数据发生改变,加入$nextTick,切换判断条件的布尔值,已达到重新渲染的效果
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- 静默刷新 -->
    <div id='app'>
        <div v-if="bol">
            <div>{{arr}}</div>
            <div>{{obj}}</div>
            <button @click="btn">更新</button>
        </div>
    </div>
    <script src='./vue.js'></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                arr: [1, 2, 3],
                obj: {
                    one: 1,
                },
                bol: true,
            },
            methods: {
                btn() {
                    this.arr[0] = parseInt(Math.random() * 100)
                    this.obj.two = parseInt(Math.random() * 100)
                    this.bol = false;
                    this.$nextTick(() => {
                        this.bol = true
                    })
                }
            },
        })
    </script>
</body>

</html>