Home > Blockchain >  how to pass data consistently from page to page in Vue Js?
how to pass data consistently from page to page in Vue Js?

Time:08-10

Currently I want to pass data from edit page to add page. So i pass the query using {path: '/test/admin/clinicvisit/add', query:{id:this.$route.params.id}}. I was able to pass the data to add page using the query however sometimes the data may not present when it refreshes a few times. Is there any possible way to make the data consistent stay in the add page ?

add.vue

  async testRoute(){
      let visitId = this.$route.query.id
      if (visitId){
        let clinicVisit = await this.api.medical.viewClinicVisit(visitId)
        this.inputs = await this.api.medical.optionsClinicVisit()

        this.$set(this.inputs.staff, "item_text", "username")
        this.$set(this.inputs.staff, "item_value", "id")
        this.$set(this.inputs.staff, "items", await this.api.profile.listStaff({}))
        if(clinicVisit.staff){
          this.$set(this.inputs.staff, "value", clinicVisit.staff)
          this.$set(this.inputs.staff, "tmp_value", clinicVisit.staff_detail.name)
        }

    mounted()
   {
    this.testRoute()
   }

CodePudding user response:

This can be done in multiple ways.

  1. Using a global store, You can use a library like Vuex to share the state between the components.
  2. Using the Local Storage, if you want to preserve the data and keep saved after hard refreshing the page.
  3. Using Session Storage, if you want to preserve the data and keep saved during the user session, but whenever the user close the browser tab it will be gone.

CodePudding user response:

When you observe that the data is not present after a few refreshes, does it dissapear from the URL in your browser, or does it just not load?

If you want the data to stay more consistently, consider using localStorage

localStorage.setItem('item_text', 'username') //Save variable in browser data
let item_text = window.localStorage.getItem('item_text') //Get variable from browser data

EDIT:

If the URL is still present in the browser window, that sounds like a weird loading bug, where your code runs before the route is parsed by Vue. You can try using a watcher instead of the "mounted" function:

watch: {
    $route: {
        immediate: true,
        handler() {
            this.testRoute()
        }
    }
}
  • Related