vue 数组和对象渲染问题

数组更新检测

  1. 在 vue 中使用数组的push()pop()shift()unshift()splice()sort()reverse() 、filter()concat() 方法时,改变数组的同时可以触发视图的变化。
  2. 注意: 有两种情况 vue 无法检测到变动的数组,分别是:

(1)直接操作数组的长度;

  (2)利用索引直接设置一个项时,例如:this.arr[indexOfItem] = newValue

代替方案如下

// Vue.set
this.$set(arr, indexOfItem, newValue)
// Array.prototype.splice
this.arr.splice(indexOfItem, 1, newValue)

对象更新检测

    export default {
        data() {
            return {
                index: 0,
                object: {
                    name: 'haha'
                }
            }
        },
        methods: {
            changeArr() {
                //   方法一: 
                 this.$set(this.object, 'age', 27)
                //   方法二:
                  this.object = Object.assign({}, this.object, {
                    age: 27
                 })
                //  方法三: ---不可行
                 this.object.age = '27'
            }
        }
    }

this.$forceUpdate()迫使 Vue 实例重新渲染。注意它仅仅影响实例本身和插入插槽内容的子组件,而不是所有子组件。
使用 v-if 在切换时,元素及它的绑定数据和组件都会被销毁并重建

猜你喜欢

转载自www.cnblogs.com/zwhbk/p/12419562.html