我知道有很多问题可以回答我的问题,但我无法让其中一个运行。我想通过使用 vue 路由器将一个字符串从组件 A 传递到组件 B。在下面的示例中,我如何从组件 B 中输出组件 A 的 'name' 的值。
组件A模板:
<form >
<input placeholder="type your name" v-model="name">
<button v-on:click="sayHello" type="submit" >Submit</button>
<script>
sayHello() {
this.$router.push({ name: 'ComponentB', params: {
name: '{this.name}'}, props:true });
}
</script>
组件 B:
<template>
<div class="container">
<h1> Hello {{$route.params.name}}!</h1>
</div>
<script>
export default {
data(){
return{
props: ['name']
}
}
}
</script>
路由器
{
path: '/ComponentB',
name: "CompB",
component: CompB,
props: true
}
仍然不知道如何在不使用 url 参数的情况下实现这一点。
如果我将 CompB 的路径更改为 ComponentsB/:name
它会起作用。
最佳答案
您的路由器属性位于您在组件 A 中声明的 this.$route
中
所以在你的情况下:
组件 A:
<script>
sayHello() {
this.$router.push({ name: 'ComponentB', query: {
name: this.name }, props:true });
}
</script>
组件 B:
<template>
<div class="container">
<h1> Hello {{ $route.query.name }}!</h1>
</div>
</template>
我建议阅读 https://router.vuejs.org/guide/essentials/passing-props.html改为使用 props 来解耦你的组件。
关于javascript - 在 vue 路由器中的两个组件之间传递 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54698980/