Reputation: 13
Vue and Vue router. What is the best option to connect value from a get request, with parameter in Vue Router? I want this.id to be replaced by a value from the api request.
const User = {
data() {
return {
loading: false,
name: null
}
},
created() {
this.fetchData()
this.$router.push({ path: /user/${this.id} })
},
watch: {
$route: "fetchData"
},
methods: {
fetchData() {
this.error = this.name = null
this.loading = true
fetch(`https://.../`, (err, post) => {
if (this.$route.params.id !== id) return
this.loading = false
if (err) {
this.error = err.toString()
} else {
this.post = post
}
})
}
}
}
Upvotes: 1
Views: 279
Reputation: 131
as you have added props: true
in the router, you will receive id
as a props
you can directly watch id instead of the whole $route
.
props: ["id"],
created() {
this.fetchData();
},
methods: {
fetchData() {
this.error = this.name = null
this.loading = true
fetch(`https://.../user/${this.id}`, (err, post) => {
this.loading = false
if (err) {
this.error = err.toString()
} else {
this.post = post
}
})
}
}
},
watch: {
id: function() {
this.fetchData()
}
}
Upvotes: 1