我如何编写 Vue 2.x 指令,使其能够检测模型中的变化?我只能绑定(bind)到元素并检测输入、按键等。但我无法检测模型何时更新。这超出了 Vue 指令的范围吗?
Vue.directive('text-validation', {
bind: function (el, binding, vnode) {
el.addEventListener('input', function(){
console.log('only gets called on input, not model updates');
});
}
});
new Vue({
el: '#app',
data: {
text: 'testing...'
},
mounted: function() {
setTimeout(function(){
this.text = 'detected change';
}.bind(this), 2000)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div id="app">
<input v-model="text" v-text-validation=""/>
</div>
最佳答案
啊,我忘记了 update
Hook 是干什么用的。我创建了一个工作片段,它按照我的意图进行 - 模型更新调用更新 Hook
Vue.directive('text-validation', {
bind: function (el, binding, vnode) {
el.addEventListener('input', function(){
console.log('got called');
});
},
update: function(el, binding, vnode) {
console.log('got called on upadate');
}
});
new Vue({
el: '#app',
data: {
text: 'testing...'
},
mounted: function() {
setTimeout(function(){
this.text = 'detected change';
}.bind(this), 2000)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div id="app">
<input v-model="text" v-text-validation=""/>
</div>
编辑
我最终在 bind() Hook 中设置了一个 watch() 。从 update() 内部触发任何类型的 DOM native 事件会导致各种无限循环。
伪代码:
var modelExp = vnode.data.directives.find(d->d.name === 'model');
vnode.context.$watch(modelExp, function(){//do what i need}, {deep, true});
这是从“VeeValidate”项目借来的,ListenerGenerator.prototype._attachModelWatcher
关于vue.js - 用于检测模型更改的 Vue 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47562456/