简体   繁体   中英

VueJS: Updating data based on query variable

In my route I have a parameter like: ?id=101

And I have some data like:

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

Now, what I want to do this: if the query parameter is present, I want to update the id in the data with the id in the query variable. I tried doing this in the fetch, as follows:

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

However, nothing happens. I also tried calling a function from the fetch , but it says the method was not defined.

Can you please help?

Ok my answer got deleted. Find the answer below:

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

More info here:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM