반응형
하위 구성 요소를 기반으로 계산된 속성
하위 구성 요소 데이터에 의존하는 계산된 속성을 만들 수 있는가?사소한 일 같지만 알아낼 수가 없어...
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
반응형
'programing' 카테고리의 다른 글
빈 Vuex Store 상태를 포착하지만 초기화할 때 계산된 속성이 이에 반응하도록 하는 방법 (0) | 2022.04.19 |
---|---|
Vuex는 이것을 저장한다.$store가 Vue.js 구성 요소에 정의되지 않음 (0) | 2022.04.18 |
Vue: v-for에서 메소드를 사용하지만 Getter가 준비되지 않음 (0) | 2022.04.18 |
문자열의 해시 함수 (0) | 2022.04.18 |
InputStream을 Java의 String으로 읽거나 변환하는 방법 (0) | 2022.04.18 |