Vue change object in array and trigger reactivity

前端 未结 3 1001
挽巷
挽巷 2021-02-07 02:36

How can I trigger an update when altering part of an object found by index in an array?

The docs show how to alter the value of an array:



        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-07 03:28

    You could update the sub-property in the array element with this.$set(). For example, to increment an x subproperty in the first two array elements (creating the sub-property if it doesn't exist):

    methods: {
      update() {
        this.$set(this.arr[0].foo, 'x', (this.arr[0].foo.x || 0) + 100)
        this.$set(this.arr[1].foo, 'x', (this.arr[1].foo.x || 0) + 100)
      }
    }
    

    new Vue({
      el: '#app',
      data() {
        return {
          arr: [
            {
              foo: {
                x: 100,
                y: 200
              }
            },
            {
              foo: {
                /* x does not exist here initially */
                y: 400
              }
            }
          ]
        };
      },
    
      methods: {
        update() {
          this.$set(this.arr[0].foo, 'x', (this.arr[0].foo.x || 0) + 100)
          this.$set(this.arr[1].foo, 'x', (this.arr[1].foo.x || 0) + 100)
        }
      }
    })
    
    
    

    arr[0]: {{ arr[0] }}

    arr[1]: {{ arr[1] }}

    codepen

提交回复
热议问题