HTML:
<div id="testVue">
<input id="test" v-model="testModel"/>
<button @click="clickMe()">Click me</button>
<button @click="showValue()">Show value</button>
</div>
Javascript
var testVue = new Vue({
el: '#testVue',
data: {
testModel: 'Hello Vue!'
},
methods: {
clickMe: function() {
$("#test").val("testing");
console.log(this.testModel);
},
showValue: function() {
console.log(this.testModel);
}
}
});
我完全理解我不应该在 Vuejs $("#test").val("testing");
中这样做,我应该像 this.testModel="测试”;
但是我不明白为什么这个基本的绑定(bind)在Vuejs中不起作用?我有很多 HTML 组件通过 jquery 更新输入框,例如 Calendar、Autocomplete 和 Select2,它们都会通过非 vuejs 方式更新输入框。
有什么简单的方法可以解决这个问题吗?
最佳答案
现在回答为时已晚,但对于将来偶然发现此问题的任何人都可以使用我的建议来处理。
I had read somewhere that
This is a jQuery problem, trigger/val() doesn't dispatch native events in some cases.
So we will dispatch native JS Event after changing values withjQuery val()
$("#test").val("testing")[0].dispatchEvent(new Event('input'))
注意事项:-
- 在Vue中,
text
和textarea
元素使用input
事件和checkboxes
,radio
和select
使用change
作为事件。因此相应地调度事件; - 我假设您使用 id 选择器
$("#test")
将其应用于单个 dom 元素,这就是我选择[0] th
元素的原因。如果你打算将它用于多个元素,那么你可以使用 for 循环来 dispatchEvent on al。
引用:- Vue Issues on Github
关于javascript - 如果通过 jquery 更新,Vuejs 绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46955230/