vue.js - 用于检测模型更改的 Vue 指令

标签 vue.js vuejs2

我如何编写 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/

相关文章:

css - Webpack 2 不会在 vue 文件中编译 css

javascript - 如何向 Vue 路由器路径添加 float 验证?

arrays - 如何在 Vue 2 组件的数组中添加和删除项目

vuejs2 - 来自路由器参数的无效 Prop 类型,预期数字得到字符串

javascript - 推送到 vuex 存储数组在 VueJS 中不起作用

javascript - Vuejs 简单的动态 v-show 使用 index 和 falsey v-if 来切换元素

javascript - 仅当元素加载时才运行 vue 组件

javascript - VueJS : global variables not reconized in components

css - 无法从 Vue 路由器链接中删除下划线

javascript - 如何从Vue js中的App.vue获取Main.js中的数据?