欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
Vue 项目:如何解决 router 传递 params 参数,在页面刷新时数据丢失
 
情况是这样,通常我们会从一个 A 页面跳转到另一个 B 页面,如果这两个页面存在数据交互的话,就会有可能发生数据丢失的情况,来一张图,可能会更加清晰明了:
 
就比如我们 A 页面有一个按钮,点击按钮将数据传递给其他页面如图所示:
 
那接下来我们就可以新建一个 A.vue 文件代码如下:
 
<template>
 
  <button @click="toB">toB</button>
 
</template>
 
<script>
 
export default {
 
  name: 'A',
 
  data() {
 
    row: {
 
      name: 'A 页面'
 
    },
 
  },
 
  methods: {
 
    toB() {
 
      this.$router.push({
 
        name: 'B',
 
        params: {
 
          row:  this.row
 
        }
 
      })
 
    }
 
  }
 
}
 
</script>
 
接着就是 B 页面接受 A 页面的数据:
 
我们可以新建一个 B.vue 页面:
 
<template>
 
  <div>{{row.name}}</div>
 
</template>
 
<script>
 
export default {
 
  name: 'B',
 
  props: ['row'],
 
}
 
</script>
 
这里之所以可以使用 props 属性来接收 row,是因为我们在路由配置文件通过设置 props 为 true 来开启了路由参数解耦:
 
{
 
  path: '/B',
 
  name: 'B',
 
  props: true,
 
  component: import('B.vue')
 
}
 
但是如果用户突然刷新了 B 页面数据会丢失,我们一般如何解决呢?大概有三种方法:
 
第一种:使用 query 查询的方式传递参数: 在 A 页面传递数据:
 
this.$router.push({
 
  name: 'B',
 
  query: {
 
    row: JSON.stringify(this.row)
 
  }
 
})
 
B 页面接受数据:
 
<template>
 
  <div>{{JSON.parse($route.query.row).name}}</div>
 
</template>
 
第二种:还是使用 params 传递参数,但是得结合 localstroage 缓存
 
比如 A 页面:
 
this.$router.push({
 
  name: 'B',
 
  params: {
 
    row: this.row
 
  }
 
})
 
B 页面接受数据: 在 created 生命周期时先缓存数据,在页面销毁时删除缓存
 
export default {
 
  name: 'B',
 
  data() {
 
    return {
 
      row: null
 
    }
 
  },
 
  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')
 
  }
 
}

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h63413.shtml