programing

VueJS - 감시자의 첫 번째 변경 사항 건너뛰기

prostudy 2022. 5. 16. 20:59
반응형

VueJS - 감시자의 첫 번째 변경 사항 건너뛰기

VueJS에서 내가 만들고 있는 앱에 대한 컴포넌트를 만들고 있는데, var가 바뀌면 컴포넌트의 다른 부분에 로직을 적용하려는 관찰자가 있어.일단 구성요소가 초기화되면, 사용자가 Axios를 통해 수행한 몇 가지 이벤트 후에 오는 서버의 일부 데이터에 의해 여전히 설정되어야 한다.이 데이터는 메인 앱에서 에미레이트된 이벤트에서 컴포넌트로 전달된다.자, 문제는 이 논리가 보통 (항상) 바뀌지 않지만, 나는 그 논리가 처음으로 적용되는 것을 원하지 않기 때문에, 깃발을 세워서 watcher에 확인하기로 결정했지만, 그것은 일어나지 않는다: 내가 그 깃발을 true로 다시 설정하는 순간 watcher는 어쨌든 발동된다.암호는 다음과 같다.

data(){
    return {
        isSet: false,
        myVar: {
            first: 0,
            second: 0
        }
    }
},
watch: {
    'myVar.first': {
        handler: function(newVal, oldVal){
            if(!this.isSet || other.condition){return}
            console.log('first triggered');
        },
        immediate: false
    },
    'myVar.second': {
        handler: function(newVal, oldVal){
            if(!this.isSet || other.condition){return}
                console.log('second triggered');
        },
        immediate: false
    }
},
methods: {
    setBus(){ // gets called on created(){}
        let self = this;
        Bus.$on('my-event', function(c){
            self.doFirstSet(c);
        });
    },
    doFirstSet(c){
        // do other setting
        if(c.someCondition){
            this.doExtraConfig(c);
        }
        this.isSet = true; // at this point is when the watchers get triggered
    },
    doExtraConfig(c){
        // do more stuff
        if('first' in c){
            this.myVar.first = c.first;
        }else if('second' in c){
            this.myVar.second = c.second;
        }
        console.log("watchers don't get triggered yet");
    }
}

깃발이 바뀌었을 때 어떻게 발포하는 걸 막을 수 있는지 아는 거 있어?

이 인스턴스가 필요하겠음.$watch()구성 요소의 임의 지점에서 데이터 요소 보기를 시작하는 방법.이렇게 하면 워처는 문서들이 지정하는 대로 Vue 인스턴스의 인스턴스화에서 바로 인스턴스화되지 않을 것이다.

"Vue 인스턴스는 인스턴스화 시 [watch] 개체의 각 항목에 대해 $watch()를 호출할 것이다."

그래서 아마 이걸 찾고 계실 겁니다.

data: {
  return() {
    data: null,
  };
},

mounted() {
  api.fetchList().then((response) => {
    this.data = response.dataFetched
    this.$watch('data', this.dataWatcher);
  });
},

methods: {
  dataWatcher() {
    // Code won't execute after this.data assignment at the api promise resolution
  },
}

이런 간단한 경우라면, 배지의 대응은 당신이 피할 수 있음에도 불구하고 더욱 직접적이다.doneFetching가변의나는 그것을 사용할 것이다.$watch()더 많은 통제가 필요하면:실제로 삭제하기 위해 호출할 수 있는 "unwatch" 기능을 반환한다(Check it out).

또한 관찰자는 에지 케이스에 사용되어야 하며 다른 관찰자 내부에서 관찰된 변수의 변동을 피해야 한다.이는 신중하게 사용하지 않을 경우 데이터와 방법 사이의 Vue 반응성의 "정형성"에 해를 끼칠 수 있다.

Badgy의 반응은 덜 거슬리고 실수를 덜 하는 것 같다.

프로젝트에서 특히 변경 사항을 추적하는 데 사용되는 전투로 입증된 방법은 다음과 같다.

export default {
  data: () => {
    dataLoaded: false,
    valueThatChanges: 'defaultValue',
  },
  mounted () {
    let self = this
    loadData().then((result) => {
      self.valueThatChanges = result
      self.$nextTick(() => { //with this we skip the first change
        self.dataLoaded = true
      })
    })
  },
  methods: {
    loadData() {
      //your implementation
      return result
    }
  },
  watch: {
    valueThatChanges: function(newValue, oldValue) {
      if (this.dataLoaded) {
        //send tracking change
        console.log('Value was changed from ' + oldValue + ' to ' + newValue + ' via interaction, not by loading')
      }
    }
  }
}

데이터 가져오기가 수행되었는지 여부를 정의하는 부울 변수를 선언하십시오.기본적으로 false로 설정doneFetching: false그리고 일단 당신의 추적이 끝나면, 당신은 로직에게 전화한다.this.doneFetching = true.

그 후에 당신은 당신의 감시자에게서 해야 할 일은 깨끗하고 단순하다.if(this.doneFetching){...}이 간단한 논리는 당신이 원하기 전에 당신의 감시자 논리가 작동되는 것을 막아야 한다.

참조URL: https://stackoverflow.com/questions/52637936/vuejs-skip-watchers-first-change

반응형