这是一个简单的程序,我将用户输入的数据从主页发送到服务器(通过 axios),获取响应并将数据发送到 App.vue。 App.vue 接收数据并将数据作为属性传递给它的所有子组件。但问题是子组件没有收到应通过 App.vue 发送的数据,或者属性绑定没有正确完成。
main.js
createApp(App)
.use(VueRouter.createRouter({
history: VueRouter.createWebHistory(process.env.BASE_URL),
routes: [
{
path: '/home',
component: Home
},
{
path: '/',
redirect: '/home'
},
{
path: '/selectOne',
component: SelectionPage,
props: true
}
]
}))
.mount('#app')
home.vue(输入数据的地方)
<template>
<RouterLink to="/selectOne">
<button type="submit" @click="submit" style="margin-top: 1rem;"> Enter</button>
</RouterLink>
</template>
export default {
// eslint-disable-next-line vue/multi-word-component-names
name: 'Home',
data() {
return {
fullInfo: {
name: '',
gender: '',
birthdate: '',
birthTime: '',
place: ''
},
table: null
}
},
methods: {
async submit() {
let response = await axios.post('/api/selectOne', {
info: this.fullInfo,
});
let tableData = response.data;
this.table = tableData;
console.log(this.table);
this.$emit('recieveData', tableData);
}
}
}
应用程序.vue
<template>
<RouterView @recieveData="dataRecieved($event)" :data="data"></RouterView>
</template>
export default {
name: 'App',
data() {
return {
data: {},
}
},
methods: {
dataRecieved(e) {
console.log(e);
this.data = e;
}
}
}
SelectionPage.vue(未收到数据)
<template>
<div>
<h1> hello {{ data }}</h1>
</div>
</template>
export default {
name: 'SelectionPage',
props: ['data'],
}
服务器正确发送响应
似乎是一种可能的竞争条件。我不会将 home.vue 按钮包裹在
<RouterLink>
中。单击按钮正在调用提交方法并同时执行路由。尝试更同步的方法:
<template>
<button type="submit" @click="submit" style="margin-top: 1rem">Enter</button>
</template>
async submit() {
let response = await axios.get('/api/selectOne', {
info: this.fullInfo,
});
let tableData = response.data;
this.table = tableData;
console.log(this.table);
this.$emit("recieveData", tableData);
this.$router.push("/selectOne"); // <-- push AFTER emit
},