gpt4 book ai didi

javascript - Vue - 无法使用 $emit 事件将数据从组件传递到父级

转载 作者:行者123 更新时间:2023-12-01 00:30:11 25 4
gpt4 key购买 nike

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

<小时/>

按钮.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>

最佳答案

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

像这样更改你的 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>

关于javascript - Vue - 无法使用 $emit 事件将数据从组件传递到父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58627799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com