我正在尝试构建一个 vue 应用程序,通过 Spotify 的 API 进行搜索来查找曲目。但我有一个问题,它说:
未捕获(承诺中)类型错误:searchTracks 不是函数
每当我调用 searchTracks 函数时。我寻找解决方案,但似乎找不到。 我有在不同文件 (useSpotify.js) 上访问 Spotify API 的代码(我仍在学习)
import { ref } from 'vue' const useSpotify = async () => { let token const id = 'MyId' const secretId = 'mySecretId' const res = await fetch('https://accounts.spotify.com/api/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ' + btoa(id + ':' + secretId) }, body: 'grant_type=client_credentials' }); token = await res.json(); console.log(token); const searchTracks = async (searchTerm) => { console.log(token) const res = await fetch(`https://api.spotify.com/v1/search?${searchTerm}&type=track`, { method: 'GET', headers: { 'Authorization': 'Bearer ' + token } }); const data = ref(null) data.value = await res.json() console.log(data.value) return data.value } return { searchTracks } } export default useSpotify
我在 vue 组件中调用它只是为了尝试一下(Login.vue)您可以转到 //searchTry 查看此尝试完成的代码
<template> <form @submit.prevent="handleLoginSubmit"> <h3>Login</h3> <input type="email" placeholder="Email" v-model="email" /> <input type="password" placeholder="Password" v-model="password" /> <div class="error" v-if="error">{{error}}</div> <button v-if="!isPending">Login</button> <button v-if="isPending" disabled>Loading..</button> </form> <input type="text" v-model="searchTerm"> <button @click="search">search</button> </template> <script> import useLogin from "@/composables/useLogin"; import { ref } from '@vue/reactivity'; import { useRouter } from 'vue-router'; // searchTry import useSpotify from '../../composables/spotifyApi/useSpotify' // searchTry export default { setup() { const {error, isPending, login} = useLogin() const router = useRouter() const email = ref('') const password = ref('') const handleLoginSubmit = async () =>{ const res = await login(email.value, password.value) if(!error.value){ router.push({name: 'UserPlaylists'}) } } // search try const searchTerm = ref('') const {searchTracks} = useSpotify() const search = async () =>{ const res = searchTracks(searchTerm.value) } // search try return{email, password, isPending, error, handleLoginSubmit, searchTerm, search} }, }; </script> <style>我不明白问题来自哪里。请帮忙(我仍然不太擅长 JavaScript,请指出我所犯的错误)
您将 useSpotify 定义为
async
函数,调用时应使用await
或then()
。异步函数的响应始终是承诺。 文档