IT이야기

Vue.js - 구성 요소에서 계산된 속성 다시 계산

cyworld 2022. 4. 17. 15:55
반응형

Vue.js - 구성 요소에서 계산된 속성 다시 계산

나는 이 문제를 직답을 찾지 못한 채 많이 찾아보았다.창 높이에 따라 달라지는 계산된 속성이 있어서 창 크기가 조정될 때마다 다시 계산해야 해.사용 시도 중$forceUpdate()부품과는 잘 안 맞는 것 같아.다음은 내 구성 요소:

Vue.component('trades-component', {

  mixins: [tradingMixin],

  created: function() {
    var that = this;
    // recompute visible trades if window resized
    $( window ).on( "resize", function() {
      that.$forceUpdate();
    });
    $( window ).resize();
  },

  computed: {

    visibleTradesCount: function() {
      var colOffset = $(".left-col").offset();
      var colHeight = $(".left-col").height();
      var tableOffset = $(".left-col #trade-history table").offset();
      var tableHeight = colHeight - (tableOffset.top - colOffset.top) - this.rowHeight;
      return Math.floor(tableHeight / this.rowHeight)
    }
  }
})

가능한 해결 방법을 알고 있지만 특정 속성 또는 구성 요소의 모든 계산된 속성을 다시 계산하도록 강제할 방법이 있는지 알고 싶다.

이것은 @BillCriswell의 대답만큼 깨끗하지는 않지만, 만약 당신의 계산에 새로 고침을 유발하는 다른 의존성이 있다면, 당신은 계산된 것을 고수하기를 원할지도 모른다.

창 너비와 높이에 대한 데이터 속성을 사용하고 계산된 속성에 참조를 추가하여 크기를 다시 계산할 수 있다.

data: function () {
  return { 
    windowWidth: 0,
    windowHeight: 0
  }
}
created: function() {
  var that = this;
  $( window ).on( "resize", function() {
    that.windowWidth =  window.innerWidth;
    that.windowHeight = window.innerHeight;
  });
  $( window ).resize();
},
computed: {
  visibleTradesCount: function() {
    const x = this.windowWidth;
    const y = this.windowHeight;
    ...

참고, 다음이 필요할 수 있음$(window).off("resize", inbeforeDestroy().

Vue가 관찰하는 내용을 업데이트하지 않기 때문에 계산된 속성을 사용할 수 없다.너는 움직일 수 있다.visibleTradesCount로부터computedmethods다음 작업을 수행하십시오.

$(window).on('resize', this.visibleTradesCount).resize()

크기 조정 이벤트만 취소하십시오.또한, 당신은 자바스크립트 없이 이것을 성취하는 것을 정말로 고려해야 한다.

참조URL: https://stackoverflow.com/questions/48550291/vue-js-recompute-computed-property-in-a-component

반응형