vue.js - How to get data from a nested component -
i have 3 components. 1 question component consists of questions. second questionoption list of choices. , third 1 main component. how data questionoption component main component. since main component not parent of questionoption cannot use $emit. make use of bus it's not working on case. can me on this.
also how chosen answers after submission of button? here code.
main.vue
<div class="quiz-background"> <question v-for="(question, $indexparent) in randomquestions" :question="question['doc'].question" :choices="question['doc']['choices']" :indexparent="$indexparent" :correctanswer="question['doc'].correctanswer" > </question> <section style="margin:16px"> <v-ons-button modifier="cta" @click="submit" v-show="!isdone" >submit </v-ons-button> </section> </div> <script> submit() { bus.$on('choosed', function(answer) { console.log(answer); }); }, </script>
question.vue
<template> <v-ons-list> <v-ons-list-header> {{indexparent + 1}}.{{ question }} </v-ons-list-header> <question-option v-for="(choice, key, $index) in choices" :choice="choice" :letter="key" :indexparent="indexparent" :index="$index" :correctanswer="correctanswer" > </question-option> </v-ons-list> </template> <script> import questionoption './questionoption.vue'; export default { props: ['question', 'indexparent', 'choices', 'correctanswer'], components: { questionoption } } </script>
questionoption.vue
<template> <v-ons-list modifier="inset"> <v-ons-list-item :name="'question-' + indexparent" :modifier="longdivider" :key="letter" tappable > <label class="left"> <v-ons-radio :name="'question-' + indexparent" :input-id="indexparent + '-' + index" :value="letter" :key="letter" v-model="chosenanswer" @change="appendanswer($event)" > </v-ons-radio> </label> <label class="center" :for="indexparent + '-' + index" :class="{'success' : issuccess, 'danger' : isdanger}" > {{ letter }} . {{ choice }} </label> </v-ons-list-item> </v-ons-list> </template> <script> import vue 'vue'; var bus = new vue(); export default { data() { return { chosenanswer: '' } }, props: ['letter', 'choice','correctanswer', 'indexparent', 'index'], computed: { issuccess () { return this.chosenanswer === this.correctanswer; }, isdanger () { return this.chosenanswer !== this.correctanswer; } }, methods: { appendanswer (event) { var answer = event.target.value; bus.$emit('choosed', answer); } } } </script>
like the article mentioned in comment, can make js file called event-bus.js
, include code below.
// event-bus.js import vue 'vue'; var eventbus = new vue(); export default eventbus;
after that, import both in questionoption.vue
, main.vue
this
import bus './event-bus';
then try again. reason why code didn't work because generated 2 vue instances, they've got no relationship each other, no communication happen.
Comments
Post a Comment