0π
β
To convert that code to Composition API:
created()
hook is effectively the same timing assetup()
, so put that code insetup()
.this.$route
can be accessed viauseRoute()
(fromvue-router@4
).artist
can be declared as a dataref
, returning it fromsetup()
if used in the template.- To reactively fetch data from the API based on the
id
parameter, usewatch
onroute.params.id
. Thiswatch
call returns a function that stops the watcher, which is useful if you need to conditionally unwatch the reference.
import { useRoute } from 'vue-router'
import { ref, watch } from 'vue'
export default {
// 1
setup() {
const route = useRoute() // 2
const artist = ref(null) // 3
// 4
const unwatch = watch(() => route.params.id, (newId, oldId) => {
const result = await axios.get(`https://localhost:5001/api/artists/${newId}`)
artist.value = result.data
// run only once
unwatch()
})
return {
artist
}
}
}
Source:stackexchange.com