[Vuejs]-Need the same functionality as a computed property, but I need to be able to update the data after initial change

1👍

Update exampleData in a watcher for item:

watch: {
  item(value) {
    this.exampleData = value;
  }
}

This way you can bind your exampleData to the textfield, but changes to the item will still affect it.

And if you want exampleData to be initially set to the value of item, do that in the component’s mounted hook:

mounted() {
  this.exampleData = this.item;
}

Here’s a fiddle.

1👍

If you set your property indata, you can initialize it in mounted which only runs once when the page is loaded:

data:
   text: null
mounted: ->
   text = "This text is initialized"

And then set v-model on your textarea

<textarea v-model="text"></textarea>

So the value of the textarea will start out as “This text is initialized”, but the user will be able to change it, and those changes will be saved in text

👤Libby

1👍

Vue already has a built-in solution to handle this if you use the getter/setter syntax for computed properties

computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}

As a result, when your state changes you can update the computer property by assigning it a value:

// state has changed in text area handler
this.fullName = 'new value'

Leave a comment