我正在嘗試構建一個 vue 應用程式,通過 Spotify 的 API 進行搜索以查找曲目。但我有一個問題,它說:
Uncaught (in promise) TypeError: searchTracks is not a function
每當我呼叫 searchTracks 函式時。我尋找了解決方案,但似乎找不到。我有訪問 Spotify API(我仍在學習)的不同檔案(使用 Spotify.js)的代碼
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 查看為這個 try 完成的代碼
<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 指出我所犯的錯誤)
uj5u.com熱心網友回復:
您將 useSpotify 定義為async函式,您應該使用await或then()在呼叫它時使用。異步函式的回應總是承諾。檔案
useSpotify().then((result) => {
const {searchTracks} = result
// rest of your code
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/371644.html
標籤:javascript 接口 Vue.js
上一篇:從可組合訪問參考值
