Home > database >  How to pass data from parent to parent in VueJs
How to pass data from parent to parent in VueJs

Time:01-31

I want to pass the property namePage from Home / About to Navbar

In router → index.js we have included the components: Home.vue and About.vue

I tried to send the data by route, but it does not work.

If I change the hook from created() to mounted(), the DOM renders the property namePage, but is not reactive to changing the Home.vue and About.vue components.

In development mode, in the VueJs tool, $route.meta.namePage is reactive.

My components:

App.vue

<template>
  <header>
    <Navbar/>
  </header>
  
  <main>
    <router-view/>
  </main>
</template>

<script>
  import Navbar from "....";
  export default {
    components: {Navbar}
  }
</script>

Navbar.vue

<template>
  <div>
    <h6> {{ namePage}} </h6>
  </div>
</template>

<script>
 export default {
   name: "Navbar",
   data() {
      return {
        namePage: ''
     }
   },
   created() {
     this.namePage = this.$route.meta.namePage;
  }
 }
</script>

Home.vue

<template>
  <div >
    text text
  </div>
</template>

<script>
 export default {
   name: 'Home',
   created() {
    this.$route.meta.namePage = 'Home page';
   }
 }
</script>

About.vue

<template>
  <div >
    text text
  </div>
</template>

<script>
 export default {
   name: 'About',
   created() {
    this.$route.meta.namePage = 'About page';
   }
 }
</script>

Use: Vue.js 3, Vuex and folder structure created with Vue CLI

CodePudding user response:

Your Navbar component is created once and always visible so the created hook will run only once.

Have you tried:

<template>
  <div>
    <h6> {{ $route.meta.namePage }} </h6>
  </div>
</template>

<script>
export default {
  name: "Navbar",
}
</script>

you can also use a watcher:

<template>
  <div>
    <h6> {{ namePage }} </h6>
  </div>
</template>

<script>
export default {
  name: "Navbar",
  data() {
    return {
      namePage: '',
    };
  },
  watch: {
    '$route.meta.namePage': {
      immediate: true, // <-- let the watcher run on initial render too
      handler: namePage => {
        this.namePage = namePage;
      },
    },
  },
}
</script>

CodePudding user response:

As you have vuex, you can easily achieve that with actions/getters. Take a look at snippet bellow with simple example:

Vue.component('Navbar', {
  template: `
    <div>
      <h3> {{ page}} </h3>
      <a href="#" @click="navigate('Home')">Home</a>
      <a href="#" @click="navigate('About')">About</a>
    </div>
  `,
  computed: {
    page() {
      return this.$store.getters.getPage //           
  •  Tags:  
  • Related