【问题标题】:Vue - Unable to Pass Data From Component to Parent with $emit EventVue - 无法使用 $emit 事件将数据从组件传递到父级
【发布时间】:2020-02-25 21:29:43
【问题描述】:

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

我浏览了上面的帖子和 Vue 文档。据我所知,我做的一切都是正确的,但它仍然无法正常工作。

我已经包含了我的代码,但恐怕我无法使用堆栈 sn-p 进行复制。可以在此code sandbox

上找到工作复制品

Buttons.vue

我在下面的 navigateTo() 函数下指出,我的控制台确认组件上的函数正在获取正确的值,但我不确定该值是由组件正确发出还是由父母。

<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>

【问题讨论】:

  • 发出事件的组件是按钮,你在场景组件上监听事件
  • 您正在&lt;scene &gt; 组件中设置'@navigate' 事件处理程序,但navigate 事件正在从&lt;button&gt; 触发。

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

发出事件的组件是按钮,您正在场景组件上监听事件:

像这样改变你的 App.vue:

<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>

【讨论】:

  • 顺便说一句,我在您的代码中没有看到 this.selectedScene 的任何用法,所以我猜您省略了一些 ...
  • 实际上this.selectedScene 在另一个组件中,所以显然我需要更正它。谢谢!
猜你喜欢
  • 2019-08-28
  • 2020-05-06
  • 2017-07-07
  • 2017-06-24
  • 2020-12-09
  • 2020-09-25
  • 2021-02-22
  • 2021-12-31
  • 2017-10-20
相关资源
最近更新 更多