Pyreal
Pyreal

Reputation: 517

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

I have a situation where I need to update data when it detects changes to a state. The user needs to be able to make further changes this info within a textarea. Using computed properties pulls in the data exactly how I want, but any changes made by the user after this are overridden because the computed property keeps changing this data back to it's initial values. What would be the best way to pull in data initially upon a state change but then allow for editing after that point?

Thanks!

Edit: Updated to what i've tried for @Libby.

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

computed: {
        ...mapGetters({
            item: 'item'
        })

methods: {
    exampleFunction() {
       this.exampleData = this.item;
}

mounted() {
    this.exampleFunction();
}

Upvotes: 0

Views: 302

Answers (3)

David L
David L

Reputation: 33883

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'

Upvotes: 1

thanksd
thanksd

Reputation: 55674

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.

Upvotes: 1

Libby
Libby

Reputation: 1022

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

Upvotes: 1

Related Questions