首页 > 解决方案 > VueJS:根据查询变量更新数据

问题描述

在我的路线中,我有一个参数,例如: ?id=101

我有一些数据,例如:

data () {
  return {
   record: {id: null}
  }
}

现在,我想做的是:如果存在查询参数,我想用查询变量中的 id 更新数据中的 id。我尝试在 fetch 中执行此操作,如下所示:

async fetch ({ store, redirect, params, query }) {
  this.record = {id: query.id}
}

然而,什么也没有发生。我也尝试从 中调用一个函数fetch,但它说该方法未定义。

你能帮忙吗?

标签: javascriptvue.js

解决方案


好的,我的答案被删除了。在下面找到答案:

export default {
  data () {
    return {
      record: {
        id: null
      }
    }
  },
  created () {
    this.fetchData()
  },
  watch: {
    '$route': 'fetchData'
  },
  methods: {
    fetchData () {
      getRecord(this.$route.query.id, (err, id) => {
        if (err) {
          this.error = err.toString()
        } else {
          this.record.id = id
        }
      })
    }
  }
}

更多信息在这里:

https://router.vuejs.org/guide/advanced/data-fetching.html


推荐阅读