Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  30] [ 6]  / answers: 1 / hits: 33169  / 9 Years ago, thu, november 5, 2015, 12:00:00

I'm new to vue.js. It seems Two-way binding of vue.js only listens to input event from user, if you change value by JS, vue.js's value is not updated



Here is an example for what I mean:





function setNewValue() {
document.getElementById('my-field').value = 'New value';
}

new Vue({
el: '#app',
data: {
message: 'Old value'
}
})

<script src=https://cdn.jsdelivr.net/vue/latest/vue.js></script>

<div id=app>
<p>{{ message }}</p>
<input id=my-field v-model=message>
</div>

<button onclick=setNewValue()>Set new value</button>





If you click Set new value button, the field's value is changed to New value but the text above it is still Old value instead of New value. But if you change the text in the field directly, the text above is changed synchronously.



Is there anyway we can do this synchronous when updating value with JavaScript?


More From » vue.js

 Answers
13

Besides using $set, as @taggon suggested, you can also work with the data model directly.





function setNewValue() {
model.message = 'New value';
}

var model = {
message: 'Old value'
},

app = new Vue({
el: '#app',
data: model
});

<script src=https://cdn.jsdelivr.net/vue/latest/vue.js></script>

<div id=app>
<p>{{ message }}</p>
<input id=my-field v-model=message>
</div>

<button onclick=setNewValue()>Set new value</button>





Or better still, manipulate the data with a method of your Vue instance, and use v-on: to handle the click event:





var app = new Vue({
el: '#app',
data: {
message: 'Old value'
},
methods: {
setNewValue: function () {
this.message = 'New value';
}
}
});

<script src=https://cdn.jsdelivr.net/vue/latest/vue.js></script>

<div id=app>
<p>{{ message }}</p>
<input id=my-field v-model=message>
<button v-on:click=setNewValue>Set new value</button>
</div>





The button must be part of the app template in this case, otherwise the v-on: event binding doesn't work.


[#64497] Tuesday, November 3, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryankiah

Total Points: 183
Total Questions: 99
Total Answers: 112

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
ryankiah questions
;