programing

하위 구성 요소를 기반으로 계산된 속성

prostudy 2022. 4. 18. 21:27
반응형

하위 구성 요소를 기반으로 계산된 속성

하위 구성 요소 데이터에 의존하는 계산된 속성을 만들 수 있는가?사소한 일 같지만 알아낼 수가 없어...

foo 성분

<template>
    {{ foo }}
</template>

<script>
export default { 
    computed: {
        foo() {
            return Math.random()
        }
    }
}
</script>

상위 구성 요소

<template>
    foo computed property sum: {{ sum }}
    <Foo v-for="n in 10"></Foo>
</template>

export default { 
    computed: {
        sum() {
            // return...?            
        }
    }
}
</script>

수 있지만, 그것은 사물에 대한 꽤 특이한 접근 방법이기 때문에, 그것은 여러분이 성취하려고 하는 어떤 것을 위한 최선의 선택은 아닐 것이다.

대신 데이터를 부모에 보관하여 구성 요소에 전달하십시오.사용한다면value소품명으로서, 당신은 몇 가지 좋은 깨끗한 구문을 얻을 수 있다.v-model. (사용해야 한다.foos[index]가명을 사용할 수 없다는 사실 때문에 그러나 이 경우에는 어쨌든 인덱스를 생성하는 것뿐입니다).

new Vue({
  el: '#app',
  data: {
    foos: []
  },
  computed: {
    sum() {
      return this.foos.reduce((a, b) => a + b, 0);
    }
  },
  components: {
    Foo: {
      template: '<div>{{ value }} <button @click="reroll">Change it</button></div>',
      props: ['value'],
      created() {
        this.reroll();
      },
      methods: {
        reroll() {
          this.$emit('input', Math.floor(Math.random() * 10));
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  foo computed property sum: {{ sum }}
  <Foo v-for="index in 10" v-model="foos[index]"></Foo>
</div>

참조URL: https://stackoverflow.com/questions/45681707/computed-property-based-on-child-components

반응형