programing

모델 변경 사항을 감지하는 Vue 지시문

prostudy 2022. 4. 13. 20:57
반응형

모델 변경 사항을 감지하는 Vue 지시문

어떻게 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>

아, 깜빡했네.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>

편집

나는 결국 훅 안에 시계()를 설치하게 되었다.업데이트() 내부에서 모든 종류의 DOM 기본 이벤트를 발생시키는 것은 모든 종류의 무한 루프를 야기하고 있었다.

유사 코드:

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

이것은 "VeValidate" 프로젝트인 ListenerGenerator.protype에서 빌렸다._attachModelWatcher

@Bert가 지적한 바와 같이 - 당신은 그것을 위해 관찰자를 사용할 수 있다/사용할 수 있다(만약 당신이 중앙 주/점포 Vuex 등 더 진보된 무언가가 필요하지 않다면).

관찰자들과 함께 - 어린이들을 물체 안에서 관찰하는 "깊이: 진실"과 함께 사용할 수 있다는 것을 주목하는 것이 매우 중요하다.

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 - 일련의 객체를 관찰하고 변경 사항을 계산하는 데 심층적인가?

참조URL: https://stackoverflow.com/questions/47562456/vue-directive-to-detect-changes-in-model

반응형