source

VueJS 딥워처 - 여러 객체의 특정 속성

goodcode 2022. 7. 28. 23:52
반응형

VueJS 딥워처 - 여러 객체의 특정 속성

문제

오브젝트가 여러 개 있는 '제품' 어레이가 있습니다.각 제품 개체에는 "가격" 속성이 포함됩니다.각 제품의 이 속성을 보고 변경 가능성을 확인하고 싶습니다.사용자가 입력란에 있는 가격을 변경할 때 수수료 가격을 계산하기 위해 사용하고 있습니다.

제품 어레이는 다음과 같습니다.

[
  0: {
    name: ...,
    price: ...,
    commission: ...,
  },
  1: {
    name: ...,
    price: ...,
    commission: ...,
  },
  2: {
    name: ...,
    price: ...,
    commission: ...,
  },
  ...
  ...
  ...
]

내 코드

시험해 봤는데, 처음 제품을 로드했을 때를 제외하고는 변화가 감지되지 않습니다.

    watch  : {
        // Watch for changes in the product price, in order to calculate final price with commission
        'products.price': {
            handler: function (after, before) {
                console.log('The price changed!');
            },
            deep   : true
        }
    },

제품은 이렇게 로딩되어 있습니다.

mounted: async function () {
            this.products = await this.apiRequest('event/1/products').then(function (products) {
                // Attach reactive properties 'delete' & 'chosen' to all products so these can be toggled in real time
                for (let product of products) {
                    console.log(product.absorb);
                    Vue.set(product, 'delete', false);
                    Vue.set(product, 'chosen', product.absorb);
                }

                console.log(products);

                return products;
            })
        }

Vue.js가 깊은 속성을 감시하는 것에 대해 살펴본 기타 질문. 이 질문은 아직 존재하지 않는 속성을 감시하려고 합니다.객체의 깊은 변경을 감시하는 VueJ 이 VueJ는 다른 컴포넌트의 변경을 감시하고 있습니다.

자세히 볼 수는 없어요.products.price가격은 제품 배열이 아니라 개별 제품의 속성이기 때문입니다.

워치 식에서 인덱스를 사용하려고 하면 선언적 워처는 배열에 문제가 있습니다.products[0].priceVue에서 경고를 받습니다.

[Vue warn] :경로 감시 실패: "products[0].price" 입니다.워처는 단순한 도트로 구분된 경로만 허용합니다.완전한 제어를 위해서는 함수를 대신 사용합니다.

, 기능이 있는 프로그램형 시계를 사용할 수 있지만 잘 설명되지 않습니다.

여기 시나리오에서 이를 수행하는 한 가지 방법이 있습니다.

<script>
export default {
  name: "Products",
  data() {
    return {
      products: []
    };
  },
  mounted: async function() {
    this.products = await this.apiRequest('event/1/products')...

    console.log("After assigning to this.products", this.products);

    // Add watchers here, using a common handler
    this.products.forEach(p => this.$watch(() => p.price, this.onPriceChanged) );

    // Simulate a change
    setTimeout(() => {
      console.log("Changing price");
      this.products[0].price= 100;
    }, 1000);
  },
  methods: {
    onPriceChanged(after, before) {
      console.log(before, after);
    }
  }
};
</script>

테스트 코드 & 박스입니다(테스트 API에는 가격이 없기 때문에 가격 대신 색상을 사용하고 있습니다).

언급URL : https://stackoverflow.com/questions/56566548/vuejs-deep-watcher-specific-property-on-multiple-objects

반응형