0
votes

What I trying to achieve here is to pass the const randomNumber inside the child component [src/components/VueForm/FormQuestion.vue] that need to be passed to parent component [src/App.vue]. Therefore I use $emit to pass the date, but since this is my first time working with $emit, I am not really sure how to do that. Could someone help me with this.

In order to run this app, I would add a working code snippet. Click on the start button and fill in the input fields. When the input field validates correctly it will pop up the button and if the user clicks on that is should pass the data to the parent. At the end it should be stored inside the App.vue in localStorage, so therefore I want to receive the randomNumber from that child component.

working code snippet here

// child component 
<template>
  <div class="vue-form__question">
    <span class="question" :class="{ big: !shouldShowNumber }"> {{ getRandomNumber() }} </span>
  </div>
</template>

<script>

export default {
  methods: {
    getRandomNumber() {
      const randomNumber = Math.floor((Math.random() * 3) + 1);
      const question = this.question.question;
      this.$emit('get-random-number', question[randomNumber]);
      return question[randomNumber];
    }
  }
};

// parent component
<template>
  <div id="app">
    <vue-form 
      :data="formData"
      @complete="complete"
      @getRandomNumber="newRandomNumber"
    ></vue-form>
  </div>
</template>

<script>
import VueForm from "@/components/VueForm";
import data from "@/data/demo";

export default {
  data() {
    return {
      formData: data
    }
  },
  components: {
    VueForm
  },
  created() {
    this.complete()
  },
  methods: {
    complete(data) {
      // Send to database here 
      // localStorage.setItem('questions', data.map(d => d.question[this.randomNumber] + ': ' + d.answer));
    },
  }
};
</script>
1

1 Answers

0
votes

v-on:get-random-number (or the superior short-hand syntax: @get-random-number). Just like you'd listen to any other event, such as @click or @mouseenter.

Though I don't know off the top of my head if dashes are valid in event names. Might have to camelcase it.