【问题标题】:how to pass data consistently from page to page in Vue Js?如何在Vue Js中从一个页面到另一个页面一致地传递数据?
【发布时间】:2022-08-16 13:54:54
【问题描述】:

目前我想将数据从编辑页面传递到添加页面。所以我使用{path: \'/test/admin/clinicvisit/add\', query:{id:this.$route.params.id}} 传递查询。我能够使用查询将数据传递到添加页面,但是有时刷新几次时数据可能不存在。有没有办法让数据保持一致地留在添加页面中?

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()
   }

  • 为什么不将其存储在浏览器“localStorage”中?
  • 我如何存储在浏览器本地存储中?

标签: javascript vue.js


【解决方案1】:

这可以通过多种方式完成。

  1. 使用global store,您可以使用Vuex 之类的库在组件之间共享状态。
  2. 使用Local Storage,如果您想保留数据并在硬刷新页面后继续保存。
  3. 使用Session Storage,如果您想在用户会话期间保留数据并继续保存,但只要用户关闭浏览器选项卡,它就会消失。

【讨论】:

  • 谢谢,会考虑你建议的方法之一
  • 我如何将其存储为本地存储?在传递给添加页面之前,我是否将其保存在我的编辑页面中?
  • 是的,请确保,如果数据是objectarray,则在set 中执行JSON.stringify(data),在local storage 中执行JSON.parse(data),当您从locale storage 中执行get 时。
  • 我使用JSON.stringify(data) 将数据设置到本地存储中。假设对象有general_amount,我如何专门获取数据并相应地设置到输入字段?
【解决方案2】:

当您在几次刷新后观察到数据不存在时,它是从浏览器中的 URL 中消失,还是只是没有加载?

如果您希望数据保持更一致,请考虑使用 localStorage

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

编辑:

如果 URL 仍然存在于浏览器窗口中,这听起来像是一个奇怪的加载错误,您的代码在 Vue 解析路由之前运行。 您可以尝试使用观察者而不是“已安装”功能:

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

【讨论】:

  • 数据未加载,但 URL 仍与 ID 保持相同
  • 这很奇怪......也许你可以尝试将你的函数移动到你的 $route 的直接观察者,以确保在你的代码运行之前加载路由器,我将在我的答案中添加一个示例。
  • nitro] [dev] [unhandledRejection] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 使用 watcher 后出现此错误
  • 你有没有试过,在你的 testRoute() 函数中,console.log(this.$route.query) 在你的函数运行之前查看它是否被正确填充。我不知道是什么导致了您描述的错误,但如果它在mounted() 中起作用,您可以尝试设置超时并在您第一次运行该函数时如果尚未填充查询则重试
  • 我试图设置一个超时,这很有帮助,非常感谢
【解决方案3】:

我通过在edit.vue 中设置超时功能解决了这个错误。

handleCreate(event){
        event.preventDefault();
        this.$router.push({path: '/medical/admin/clinicvisit/add', query:{id:this.$route.params.id}},2000)
        // now 'this' is referencing the Vue object and not the 'setTimeout' scope
        this.loadClinicVisitData = true;
        setTimeout(() => this.loadClinicVisitData = false,1000)
    }

【讨论】:

    猜你喜欢
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 2019-11-03
    • 2020-11-20
    • 2023-03-30
    • 2017-01-25
    相关资源
    最近更新 更多