我正在使用 Vue(和 Laravel for RESTful API)構建一個相當大的 SPA。我很難在網上找到有關此的資源 - 組織與服務器通信的代碼的好做法是什么?目前我有src/api.js文件,它使用axios并定義了一些基本方法以及特定的 API 端點(被截斷):import axios from 'axios';axios.defaults.baseURL = process.env.API_URL;const get = async (url, params = {}) => (await axios.get(url, { params }));const post = async (url, data = {}) => (await axios.post(url, data));export const login = (data) => post('users/login', data);然后在我的組件中,我可以做...<script>import { login } from '@/api';...methods: { login() { login({username: this.username, password: this.password}) .then() // set state .catch() // show errors }}</script>這是一個好習慣嗎?我要我的終點分成多個文件(例如auth,users,documents等)?這種事情有沒有更好的設計,尤其是在涉及重復(例如錯誤處理、顯示加載條等)時?謝謝!
如何在 Vue 單頁應用程序中構建 API 代碼?
楊__羊羊
2021-06-30 13:09:37