duke
duke

Reputation: 101

VueJS: Pass Data Between Routers

I have tried countless to pass data between views using props and can't seem to get it to work. The idea is to pass data from one route to the other and at the end display all user inputted data.

Component A

<script>
export default {
  name: 'DependencyStatus',
  data: function () {
    return {
      efcForm: {
        born: false
      }
    }
  },
  methods: {
    processForm: function () {
      this.$router.push({name: 'student', props: {messaged: 1}})
      console.log({born: this.efcForm.born,})
    }
  }
}
</script>

Component B

<script>

export default {
  name: 'StudentData',
  props: ['messaged'],
  data: function () {
      return {
          born: this.$route.messaged
      }
  },
  methods: {
      checkForm: function() {
          console.log({checkForm: this.born })
      }
  }
  
}
</script>

My routes:

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/student',
    name: 'student',
    component: Student,
    props: true
  },

Upvotes: 0

Views: 123

Answers (1)

Shivam Singh
Shivam Singh

Reputation: 1731

You can use dynamic param to pass data from one route component to another.

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/student/:messaged', // <-- [1] Add dynamic param
    name: 'student',
    component: Student,
    props: true
  }
]

Component A:

methods: {
 processForm: function () {
  this.$router.push({name: 'student', params: { messaged: 1 } }) // <-- [2] pass `messaged` as param instead of prop
 }
}

Component B:

methods: {
 checkForm: function() {
  console.log({ messaged: this.$route.params.messaged }) // <-- [3] excess in the other component via route param
 }
}

PS: In case of passing complex ds, consider using Vuex

Upvotes: 1

Related Questions