用于检测模型更改的 Vue 指令

Eli*_*jah 4 vue.js vuejs2

如何编写 Vue 2.x 指令以检测模型中的更改?我只能绑定到元素并检测输入、按键等。但是我无法检测模型何时更新。这是否超出了 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)
  }
})    
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Eli*_*jah 6

啊,我忘记update钩子是干什么用的了。我创建了一个工作片段,它符合我的意图 - 模型更新调用更新钩子

 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)
  }
})    
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

编辑

我最终在 bind() 钩子内设置了一个 watch() 。从 update() 内部触发任何类型的 DOM 本机事件都会导致各种无限循环。

伪代码:

var modelExp = vnode.data.directives.find(d->d.name === 'model');
vnode.context.$watch(modelExp, function(){//do what i need}, {deep, true});
Run Code Online (Sandbox Code Playgroud)

这是从“VeeValidate”项目中借用的,ListenerGenerator.prototype._attachModelWatcher