每当用户切换到表单中的另一个字段时,我想触发一个方法。这样做了:
new Vue({
el: "#root",
data: {
theContent1: "",
theContent2: ""
},
methods: {
changeFun() {
console.log('change')
}
}
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.js"></script>
<div id="root">
<form>
<input v-model="theContent1" @change="changeFun()">
<input v-model="theContent2" @change="changeFun()">
</form>
</div>
&#13;
当有许多字段时,它是重复的。 有没有办法全局绑定到任何更改的方法?
注意:我不想在watch
的内容上设置data
- 当编辑的元素更改时,我需要使用该方法进行trigerred,而不是内容可以。一个实际的例子是,一旦一个字段完成并且用户离开它就会提交(但是在编辑字段时每次更改字段时都不会提交)。
答案 0 :(得分:3)
只需将您的事件监听器放在div的根目录下即可。 All Dom events traverse the Dom down from the root, to the element that generated the event, then back up again !你可以在任何级别听取他们的意见。使用event.target
和event.currentTarget
查看生成事件的内容以及捕获事件的内容。
请注意,出于这个原因,停止传播事件是非常激进的。元素之上的各种事物可能对它生成的事件感兴趣。
new Vue({
el: "#root",
data: {
theContent1: "",
theContent2: ""
},
methods: {
changeFun(event) {
console.log('change from '+event.target.id)
}
}
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.js"></script>
<div id="root" @change="changeFun">
<form>
<input id="one" v-model="theContent1">
<input id="two" v-model="theContent2">
</form>
</div>
&#13;
答案 1 :(得分:1)
你可以使用观察者:
new Vue({
el: "#root",
data: {
theContent1: "",
theContent2: ""
},
watch: {
theContent1(newVal) {
console.log('change from theContent1: ', newVal)
},
...
}
})
有了这个,你也必须为每个人设置观察者......