VueJS dynamic property name not updating value

前端 未结 2 1184
感情败类
感情败类 2021-01-06 08:06

I am trying to implement an associated array combined with accessing the property within the value, the key is based on the value of the campaign object.

<         


        
2条回答
  •  春和景丽
    2021-01-06 08:48

    This is happening due to caveats of reactivity in vue.js. You have just defined configuration: {} initially in data, so configuration[key] are not reactive. To make these reactive, you have to use this.$set:

    Set a property on an object. If the object is reactive, ensure the property is created as a reactive property and trigger view updates. This is primarily used to get around the limitation that Vue cannot detect property additions.

    use like following:

    this.campaigns.forEach((campaign) => {
      var id = campaign._id;
      this.$set(this.configuration, id, {'value': 'default value'})
    })
    

    var app = new Vue({
      el: '#app',
    
      data: {
        campaigns: [],
        configuration: {}
      },
    
      mounted: function() {
        this.campaigns = [{
          _id: 'abcdefg'
        }, {
          _id: 'kejwkfe'
        }, {
          _id: 'iruwiwe'
        }, {
          _id: 'reiwehb'
        }];
    
        this.campaigns.forEach((campaign) => {
          var id = campaign._id;
          this.$set(this.configuration, id, {'value': 'default value'})
        })
      }
    })
    
    
    • {{ configuration[campaign._id].value }}

提交回复
热议问题