简体   繁体   English

在vue路由器中的两个组件之间传递道具

[英]Pass props between two components in vue router

I know there are a lot of questions who answer my question but I can't get single of them run. 我知道有很多问题可以回答我的问题,但是我无法让他们一个人跑。 I want to pass a string from component A to component B by using vue router. 我想使用vue路由器将字符串从组件A传递到组件B。 In the following example how can I output the value of 'name' from component A in component B. 在以下示例中,如何从组件B中的组件A输出'name'的值。


Component A template: 组件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>

Component B: 成分B:

<template>
<div class="container">
    <h1> Hello {{$route.params.name}}!</h1>
      </div>

    <script>
export default {
    data(){
        return{
            props: ['name']
        }
    }
}
</script>

router 路由器

{
  path: '/ComponentB',
  name: "CompB",
  component: CompB,
  props: true
}

Still don't know how I can achive this without using url params. 仍然不知道如何在不使用url参数的情况下实现这一目标。 If I change the path of CompB to ComponentsB/:name it works. 如果我将CompB的路径更改为ComponentsB/:name它将起作用。

Your router properties are in this.$route which you have declared in Component A 您的路由器属性在组件A中声明的this.$route

So in your case: 因此,在您的情况下:

Component A: 成分A:

<script>
sayHello() {
     this.$router.push({ name: 'ComponentB', query: {
        name: this.name }, props:true });
    }
</script>

Component B: 成分B:

<template>
 <div class="container">
    <h1> Hello {{ $route.query.name }}!</h1>
 </div>
</template>

I would suggest reading https://router.vuejs.org/guide/essentials/passing-props.html to decouple your component using props instead. 我建议阅读https://router.vuejs.org/guide/essentials/passing-props.html来使用props解耦您的组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM