[Vuejs]-Compute not updating if radio is checked through code

1👍

You don’t need jQuery for this – just bind the values to one array and use @focus event on the textarea:

new Vue({
  el: "#app",
  data: {
    values: ['', 'Hi', ''],
    selected: '',
  },
  computed: {
    selectedText: function() {
      return this.values[this.selected];
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">

  Selected option 1: {{ selectedText }}
  <BR/>

  <input type="radio" name="item1" value="0" v-model="selected" /> Empty
  <BR/>
  <input type="radio" name="item1" value="1" v-model="selected" /> Hi
  <BR />
  <input type="radio" name="item1" value="2" v-model="selected" />

  <textarea name="textarea0" id="textarea0" cols="30" rows="10" v-model="values[2]" @focus="selected = '2'"></textarea>

</div>

Also the JSFiddle.

👤Vucko

1👍

Update

As the questioner choose another answer, but i don’t think that is the key point.

The reason is $forceUpdate() only force the view to re-render, not the computed properties. See the issue forceUpdate does not update computed fields

And i create a simple jsfiddle to descript it.


Raw Answer

The problem you faced is that vuejs cannot detect array change in some situation. You can see more detail in the doc vuejs list rendering

So the solution is replaced these code

this.selected[0] = '**custom**';
this.$forceUpdate();

with

this.$set(this.selected, 0, '**custom**')

0👍

While writing the answer I got an idea and it seems to work. However I still want to know if there is a “right” way of doing things which I’m missing.

The fix was to “click” the radio button instead of “checking” it:

$(e.target).prev().click();
👤gX.

Leave a comment