programing

연결된 데이터가 변경된 후 Vue 구성 요소가 즉시 업데이트되지 않음

prostudy 2022. 6. 17. 21:37
반응형

연결된 데이터가 변경된 후 Vue 구성 요소가 즉시 업데이트되지 않음

저는 아직 Vue가 처음이라 연결된 데이터가 업데이트되는 즉시 컴포넌트의 내용을 업데이트해야 하는 데 어려움을 겪고 있습니다.단, 컴포넌트는 재렌더되는 즉시 변경된 내용을 표시합니다.

요소

Vue.component('report-summary', {
  props: ['translation', 'store'],
  watch: {
    'store.state.currentModel.Definition': {
      handler: function(change) {
        console.log('Change detected', change);
      },
      deep:true
    }
  },
  template: '<div>
    '<div class="alert alert-secondary" role="alert">' +
    '<h5 class="border-bottom border-dark"> {{ translation.currently_defined }}</h5>' +
    '<div>{{ store.state.currentModel.Definition.length }} {{translation.elements }}</div>' +
    '</div>' +
    '</div>'
});

store는 페이지의됩니다.

<report-summary :translation="t" :store="store"></report-summary>

store그 자체가 Vuex입니다.스토어:

let store = new Vuex.Store({
  state: {
    t: undefined,
    currentModel: undefined
  },
  mutations: {
    storeNewModel(state) {
      let model = CloneFactory.sealedClone(
        window.Project.Model.ReportTemplateModel);
      model.Header = CloneFactory.sealedClone(
        window.Project.Model.ReportTemplateHeaderModel);
      state.currentModel = model;
    },
    storeNewModelDefinition(state, definition) {
     state.currentModel.Definition.push(definition);
    }
  }
});

currentModel은 「」를 호출하는 입니다.store.commit('storeNewModel');Definition여하하다

의의 the the의 、 의음 、 the the 、 the the 、 the the the the the the the 。store.commit('storeNewModelDefinition')「 」:

for (let c in this.$data.currentDefinition.charts) {
  store.commit('storeNewModelDefinition', c);
}

store.commit('storeNewModelDefinition', c);.

Vuex%20 Store|325 x 190

단, 컴포넌트는 변경된 데이터에 반응하지 않습니다.

미%20 갱신 | 553 x 110

그런 다음 내장 컴포넌트를 숨기는 보기를 변경하여 다른 곳으로 이동한 후 다시 콘텐츠가 업데이트된 보기로 이동합니다.

갱신 | 476 x 112

콘솔 창에 워처가 트리거되지 않은 것이 표시됩니다.

console | 681x198

내가 뭘 놓쳤지?미리 눈을 뜨게 해줘서 고마워요.

EventBus 사용

watch이벤트 버스 청취자에게도 예정대로 작동하지 않았습니다.

EventBus의 초기화는 다음과 같습니다.

window.eventBus= new Vue(); 

컴포넌트에 다음 항목을 추가했습니다.

  created: function() {
    window.eventBus.$on('report-summary-update', function() {
      this.$nextTick(function(){ this.$forceUpdate(); });
    });
  }

또한 목록에서 요소를 추가하거나 삭제한 후 이벤트를 내보냅니다.

window.eventBus.$emit('report-summary-update');

때 " " "를 .this.$forceUpdate();호출 중이지만 UI는 이전 콘텐츠를 변경하지 않고 표시합니다.★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★


추신: 는 이것을 Vue 포럼에 크로스 투고했습니다만, 커뮤니티가 작은 편이기 때문에, 여기서 피드백을 받을 수 있습니다.

데이터를 중첩된 배열에 푸시하면 항상 구성 요소가 업데이트되지 않는 이러한 문제가 발생합니다.

스토어에 getter를 추가하고 해당 getter를 사용하여 스토어에서 데이터를 가져옵니다.

let store = new Vuex.Store({
  state: {
    t: undefined,
    currentModel: undefined
  },
  mutations: {
    storeNewModel(state) {
      let model = CloneFactory.sealedClone(
        window.Project.Model.ReportTemplateModel);
      model.Header = CloneFactory.sealedClone(
        window.Project.Model.ReportTemplateHeaderModel);
      state.currentModel = model;
    },
    storeNewModelDefinition(state, definition) {
     state.currentModel.Definition.push(definition);
    }
  },
  getters:{
    definitions(state){
      return state.currentModel.Definition
    }
  }
});

컴포넌트에 스토어에서 데이터를 가져오는 계산 프로포트를 추가할 수 있습니다.

Vue.component('report-summary', {
  props: ['translation', 'store'],
  computed: {
    definitions(){
     return store.getters.definitions
    }
  },
  template: '<div>
    '<div class="alert alert-secondary" role="alert">' +
    '<h5 class="border-bottom border-dark"> {{ translation.currently_defined }}</h5>' +
    '<div>{{ definitions.length }} {{translation.elements }}</div>' +
    '</div>' +
    '</div>'
});

UPDATE (2019년 11월 30일)상기 코드가 아직 기능하지 않는 경우,storeNewModelDefinition 환::

storeNewModelDefinition(state, definition) {
     // Create a new copy of definitions
     let definitions = [...state.currentModel.Definition]

     // Push the new item
     definitions.push(definition)

     // Use `Vue.set` so that Vuejs reacts to the change
     Vue.set(state.currentModel, 'Definition', definitions);
    }

EventBus 실험 관련 참고 사항(반응성 문제를 해결하려고 노력하지 말고$forceUpdate)

EventBus 실험이 성공하지 못한 이유는 익명 함수를 이벤트 핸들러로 사용하기 때문입니다.이 코드를 보세요.

  methods: {
    onEvent() {
      console.log(this)
    }
  },
  mounted() {
    // this.onEvent is method where "this" is bound to current Vue instance
    this.$bus.$on("test", this.onEvent);
    // Handler is anonymous function - "this" refers to EventBus Vue instance
    this.$bus.$on("test", function() {
      console.log(this)
    });
  }
  • 1t 이벤트 핸들러는 다음과 같은 기능입니다.this(Vue 자체에 의해) 명시적으로 Vue 인스턴스에 바인드되어 있습니다.이 인스턴스는 핸들러가 "존속"하고 있습니다.
  • 두 번째 이벤트 핸들러는 익명 함수입니다.this명확하게 묶여 있지 않기 때문에, 결과적으로this == event bus Vue instance. 클로저를 사용하여 다음과 같이 작업을 수행할 수 있습니다.
  mounted() {
    let self = this;
    this.$bus.$on("test", function() {
       // self = "this" in context of function "mounted"
       console.log(self)
    });
  }

thisJS에서는 까다로울 수 있습니다.

vuejs 문서의 상세 반응성 섹션 참조

Vue가 데이터 개체를 변환하고 반응하도록 하려면 속성이 데이터 개체에 있어야 합니다.

이것은 일회성 반응성 경고입니다.Vue가 속성 추가 또는 삭제를 감지할 수 없습니다.

대신 당신의 주에서currentModel: undefined반응하고 싶은 모든 속성을 추가합니다.

currentModel: { definitions:[] }

요소 추가 또는 제거definitions어레이가 자동으로 반응하게 됩니다.

설명서에서 자세한 내용을 찾을 수 있습니다.

깊이에서의 반응성

변경 감지 경고

언급URL : https://stackoverflow.com/questions/59107201/vue-component-not-immediately-updating-after-associated-data-changes

반응형