首頁  >  問答  >  主體

使用Vue從JavaScript檔案呼叫REST API

<p>我有一個在Vue頁面上完美運行的Axios API呼叫。我需要將其變成一個獨立的可調用模組,以便在應用程式中多次重複使用。每次嘗試都失敗了,我不確定是缺乏對獨立js的經驗還是其他原因。 </p> <p>這是可工作的Vue程式碼。 </p> <pre class="lang-html prettyprint-override"><code><template> <div> <ul v-if="posts && posts.length"> <li v-for="post of posts"> <p><strong>{{post.resID}}</strong></p> <p>{{post.Name}}</p> </li> </ul> <ul v-if="errors && errors.length"> <li v-for="error of errors"> {{error.message}} </li> </ul> </div> </template> <script> import axios from 'axios'; export default { name: "GetMxList", data() { return { posts: [], errors: [] } }, // 在元件建立時取得貼文。 created() { axios.get("http://localhost:8080/rest/...") .then(response => { // JSON回應會自動解析。 this.posts = response.data }) .catch(e => { this.errors.push(e) }) } } </script> </code></pre> <p>Vue 3。謝謝你的回答。抱歉我沒有表達清楚。我的目標是創建一個模組(類似於rest.js),然後在Pinia中使用它。目的是加載一次,然後經常使用結果。目前,它可以透過類似以下程式碼的「靜態」載入來運作,其中getJSONList呼叫傳回一個JSON格式的答案,並將該答案放入MyList中以供整個應用程式使用。因此,組件只需使用Pinia映射。 </p> <pre class="brush:php;toolbar:false;">actions: { async fetchList() { const data = await getJSONList(); this.Mylist = data; },</pre> <p>很多次迭代。雖然這不會回傳任何內容,但至少不會拋出任何錯誤...</p> <pre class="brush:php;toolbar:false;">import axios from 'axios'; export function getJSONList() { const rest = axios.create({ baseURL: "http://localhost:8080/rest/", // 更好的做法是使用環境變量 }); const getPosts = async () => { try { return (await rest.get("http://localhost:8080/rest/")).data; } catch (err) { console.error(err.toJSON()); throw new Error(err.message); } }; return (getPosts); }</pre></p>
P粉170858678P粉170858678416 天前513

全部回覆(1)我來回復

  • P粉464208937

    P粉4642089372023-08-30 09:34:20

    通常,你只需要將Axios部分移入一個模組,並將資料的使用留給你的元件。

    // services/rest.js
    import axios from "axios";
    
    const rest = axios.create({
      // 更好的方式是使用环境变量来定义你的URL
      baseURL: "http://localhost:8080/rest/tctresidents/v1",
    });
    
    // 这是一个函数
    export const getResidents = async () => {
      try {
        // 请求路径将会附加到baseURL后面
        return (await rest.get("/Residents")).data;
      } catch (err) {
        // 参考 https://axios-http.com/docs/handling_errors
        console.error(err.toJSON());
    
        throw new Error(err.message);
      }
    };
    

    然後在你的元件/儲存/任何地方...

    import { getResidents } from "./path/to/services/rest";
    
    export default {
      data: () => ({ residents: [], errors: [] }),
      async created() {
        try {
          this.residents = await getResidents();
        } catch (err) {
          this.errors.push(err);
        }
      },
    };
    

    回覆
    0
  • 取消回覆