简体   繁体   English

当绑定输入字段的值被JavaScript更改时,自动更新vue.js数据

[英]Update vue.js data automatically when binded input field's value is changed by JavaScript

I'm new to vue.js. 我是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 似乎vue.js 的双向绑定只监听来自用户的输入事件,如果你通过JS改变值,则vue.js的值不会更新

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? 无论如何我们可以在使用JavaScript更新值时同步吗?

Besides using $set , as @taggon suggested, you can also work with the data model directly. 除了使用$set ,如@taggon所建议的那样,您还可以直接使用数据模型。

 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: 或者更好的是,使用Vue实例的方法操作数据,并使用v-on:来处理click事件:

 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. 在这种情况下, button必须是app模板的一部分,否则v-on:事件绑定不起作用。

Use $set instead of accessing the DOM element directly. 使用$set而不是直接访问DOM元素。 Do not mutate the model through DOM API. 不要通过DOM API改变模型。

 function setNewValue() { app.$set(app.$data, 'message', 'New value'); } var app = 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM