0
votes

Pass data from child to parent in Vuejs (is it so complicated?)

Can't pass data from children to parent component with emit

$emit an event from child to parent component Vue 2

I've looked through the posts above and the Vue documentation. From what I can see, I'm doing everything right, but it's still not working.

I've included my code but I'm afraid that I'm unable to a reproduction with a stack snippet. A working reproduction can be found here on this code sandbox


Buttons.vue

I've noted below under the navigateTo() function that my console confirms that the function on the component is getting the correct value, but I'm not sure that the value is being properly emitted by the component or received by the parent.

<template>
  <div class="navigation section columns">
    <div class="container column has-text-centered" v-for="button in navigation" :key="button.text">
      <button class="button is-primary" @click="navigateTo(button)" type="button">{{ button.text }}</button>
    </div>
  </div>
</template>
<script>
export default {
  name: "Buttons",
  props: {
    text: String,
    dest: String
  },
  computed: {},
  methods: {
    navigateTo(button) {
      // This console log correctly outputs "button dest 2"(or whatever the button value is)
      console.log("button dest", button.dest);
      this.$emit("navigate", button.dest);
    }
  },
  data() {
    return {
      navigation: [
        { text: "North", dest: "2" },
        { text: "East", dest: "3" },
        { text: "South", dest: "4" },
        { text: "West", dest: "5" }
      ]
    };
  }
};
</script>

App.vue

<template>
  <div id="app" class="container">
    <scene @navigate="navigateTo"></scene>
    <buttons></buttons>
  </div>
</template>

<script>
import Scene from "./components/Scene.vue";
import Buttons from "./components/Buttons.vue";

export default {
  name: "app",
  methods: {
    navigateTo(dest) {
      console.log('received value', dest);
      this.selectedScene = dest;
    }
  },
  components: {
    Scene,
    Buttons
  }
};
</script>
<style scoped>
</style>
1
The component emitting the event is the button and you are listening to the event on the scene componentM. Gara
You're setting up the '@navigate' event handler in the <scene > component, yet the navigate event is being fired from <button>.Sergeon

1 Answers

3
votes

The component emitting the event is the button and you are listening to the event on the scene component:

Change your App.vue like this :

<template>
  <div id="app" class="container">
    <scene ></scene>
    <buttons @navigate="navigateTo" ></buttons>
  </div>
</template>

<script>
import Scene from "./components/Scene.vue";
import Buttons from "./components/Buttons.vue";

export default {
  name: "app",
  methods: {
    navigateTo(dest) {
      console.log('received value', dest);
      this.selectedScene = dest;
    }
  },
  components: {
    Scene,
    Buttons
  }
};
</script>
<style scoped>
</style>