Vue project: How to solve the problem that the router passes params parameter and loses data when the page is refreshed

The situation is that we usually jump from one page A to another page B. If there is data interaction between the two pages, data loss may occur. Here is A picture, which may be more clear:

For example, there is A button on page A. Click the button to transfer data to other pages, as shown in the figure below:

Then we can create a new a. vue file with the following code:



<template>

  <button @click="toB">toB</button>

</template>

<script>

export default {

  name: 'A',

  data() {

    row: {

Name: 'A page '

    },

  },

  methods: {

    toB() {

      this.$router.push({

        name: 'B',

        params: {

          row:  this.row

        }

      })

    }

  }

}

</
script>

Copy the code

Then page B receives the data from page A:

We can create a new B.ue page:

<template>

  <div>{{row.name}}</div>

</template>



<script>

export default {

  name: 'B',

  props: ['row'],

}

</
script>

Copy the code

The reason we can use the props attribute to receive the row is because we enable route parameter decoupling in the routing configuration file by setting the props to true:

{

  path'/B'.

  name'B'.

  propstrue.

  componentimport('B.vue')

}

Copy the code

But if the user suddenly refreshes page B, the data will be lost. How do we solve this problem? There are roughly three ways:

The first option is to pass the parameter as A query:



this.$router.push({

  name'B'.

  query: {

    rowJSON.stringify(this.row)

  }

})

Copy the code

B page accepts data:

<template>

  <div>{{JSON.parse($route.query.row).name}}</div>

</template>

Copy the code

The second option is to pass parameters using params, but in combination with the Localstroage cache

For example, page A:

this.$router.push({

  name'B'.

  params: {

    rowthis.row

  }

})

Copy the code

B pages accept data: Data is cached during the Created life cycle and the cache is deleted when the page is destroyed

export default {

  name'B'.

  data() {

    return {

      rownull

    }

  },

  created() {

    let rowData = localStorage.getItem('rowData')

    if(rowData) {

      this.row = this.$route.params.row

      localStorage.setItem('rowData'.JSON.stringify(this.$route.params.row))

    }

  },

  beforeDestory() {

    localStorage.removeItem('rowData')

  }

}

Copy the code

Third: Use Vuex warehouse to store data: