简体   繁体   中英

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. In the following example how can I output the value of 'name' from component A in component B.


Component A template:

<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:

<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. If I change the path of CompB to ComponentsB/:name it works.

Your router properties are in this.$route which you have declared in Component A

So in your case:

Component A:

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

Component 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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