【发布时间】: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>
【问题讨论】:
-
发出事件的组件是按钮,你在场景组件上监听事件
-
您正在
<scene >组件中设置'@navigate' 事件处理程序,但navigate事件正在从<button>触发。
标签: javascript vue.js vuejs2 vue-component