如何编写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)
}
}) <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>
发布于 2017-11-30 07:12:15
啊,我忘了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)
}
}) <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()钩子中设置了watch()。从update()内部触发任何类型的DOM本机事件都会导致各种无限循环。
伪码:
var modelExp = vnode.data.directives.find(d->d.name === 'model');
vnode.context.$watch(modelExp, function(){//do what i need}, {deep, true});这是从“ListenerGenerator.prototype._attachModelWatcher”项目"VeeValidate“借来的
发布于 2017-11-30 06:23:55
正如@Bert指出的那样,你可以/可以使用观察者(如果你不需要更高级的东西-比如中央、州/商店、Vuex等)。
使用观察器--需要注意的是,你可以将它们与"deep: true“一起使用,也就是观察物体内部的孩子;
watch: {
myData: {
handler: function (newVal, oldVal) {
// we have new and old values
},
deep: true /* we will be notified of changes also if myData.child is changed :) */
}
}状态更复杂,但如果应用程序变得越来越复杂,它可以成为救世主……
我找到了这个简单实用的演示:Vue - Deep watching an array of objects and calculating the change?
https://stackoverflow.com/questions/47562456
复制相似问题