如何使用 Axios 使用 Vue 3 Composition API 按 Id 获取项目

How to get item by Id using Vue 3 Composition API using Axios

我在使用 Axios 和 useRoute 使用 Axios with Composition API 时遇到困难。这是有关如何使用选项 API 执行此操作的代码,我该如何重新创建它,Vue-router 文档现在根本没有很好的记录。

async created() {
    const result = await axios.get(`https://localhost:5001/api/artists/${this.$route.params.id}`
    );
    const artist = result.data;
    this.artist = artist;
  },

将该代码转换为组合 API:

  1. created() 挂钩实际上与 setup() 的时间相同,因此将该代码放在 setup().
  2. this.$route 可以通过 useRoute()(来自 vue-router@4)访问。
  3. artist 可以声明为数据 ref,如果在模板中使用,则从 setup() 返回它。
  4. 要根据 id 参数从 API 中被动获取数据,请使用 watch on route.params.id. This watch call returns a function that stops the watcher,这在您需要有条件地取消监视引用时很有用。
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
     }
  }
}