這可能有點痛苦。您可以考慮使用VueX以獲得更優雅的圖案。
順便說一句,你說的一切都在你的問題。只需使用事件從小孩到父母溝通。
這裏有一種方法:
Vue.component('Question', {
template: `<div>
{{ name }}:
<input type="text"
@input="toogleFilled($event.target.value)">
</input>
</div>`,
props: ['name'],
methods: {
toogleFilled(inputValue) {
// Emit name of the component and true if input is filled...
this.$emit('filled', this.name, !!inputValue.length);
}
}
});
Vue.component('QuestionGroup', {
template: `<div>
<template v-for="(q, key) in questions">
<question :name="key" @filled="toogleReady">
</question>
</template>
</div>`,
data() {
return {
// Each key will be the name of the question
// Each value will be if it's filled or not
questions: {
'Question1': false,
'Question2': false
}
};
},
methods: {
toogleReady(name, filled) {
this.questions[name] = filled;
// Check if each question is filled, if yes, emit true
if (filled && Object.values(this.questions).every(q => q)) {
this.$emit('readyToSwipe', true);
} else {
this.$emit('readyToSwipe', false);
}
}
}
});
Vue.component('Survey', {
template: `<div>
\t <button :disabled="isDisabled">I'm doing nothing</button>
<question-group @readyToSwipe="toogleDisabled"></question-group>
</div>`,
data() {
return {
isDisabled: true
};
},
methods: {
toogleDisabled(ready) {
// Disable the button if the question-group is not ready
this.isDisabled = !ready;
}
}
});
new Vue({
el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app">
<survey></survey>
</div>