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文档。从我所看到的来看,我所做的一切都正确,但是仍然无法正常工作。
我已经包含了我的代码,但恐怕我无法使用堆栈代码片段进行复制。在此code sandbox
上可以找到有效的复制品我在下面的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>
<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>
答案 0 :(得分:2)
发出事件的组件是按钮,您正在场景组件上监听事件:
像这样更改您的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>