Vue change object in array and trigger reactivity

前端 未结 3 995
挽巷
挽巷 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:15

    Here is another demo example that I think give a good illustration of the reactivity of objects inside an array. Try it live here: https://codepen.io/antoniandre/pen/ZdjwKG

    JS

    new Vue({
      el: "#app",
      data: {
        array: []
      },
    
      methods: {
        addTimeProp() {
          this.array.forEach(item => {
            this.$set(item, 'time', null)
          })
        },
        updateTimeProp() {
          this.array.forEach(item => {
            item.time = (new Date()).toString()
          })
        }
      },
    
      created () {
        this.array.push({ name: 'today' }, { name: 'tomorrow' })
      }
    })
    

    HTML: PUG

    #app
      h1 Reactivity of objects inside an array
      h2 Content of the array
      pre {{ array }}
      button(@click="array.push({ name: 'another day' })") Add another object
      button(@click="addTimeProp") Add `time` property
      button(@click="updateTimeProp") Update `time` property
    

提交回复
热议问题