1
votes

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.

1

1 Answers

2
votes

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.