楊__羊羊
2021-06-30 13:09:37
我正在使用 Vue(和 Laravel for RESTful API)構(gòu)建一個(gè)相當(dāng)大的 SPA。我很難在網(wǎng)上找到有關(guān)此的資源 - 組織與服務(wù)器通信的代碼的好做法是什么?目前我有src/api.js文件,它使用axios并定義了一些基本方法以及特定的 API 端點(diǎn)(被截?cái)啵篿mport 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>這是一個(gè)好習(xí)慣嗎?我要我的終點(diǎn)分成多個(gè)文件(例如auth,users,documents等)?這種事情有沒(méi)有更好的設(shè)計(jì),尤其是在涉及重復(fù)(例如錯(cuò)誤處理、顯示加載條等)時(shí)?謝謝!
2 回答

人到中年有點(diǎn)甜
TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
如果您使用 Vue CLI,它將設(shè)置一個(gè)基本的項(xiàng)目結(jié)構(gòu)。帶有一個(gè) HelloWorld 組件。您將希望將您的 vue 應(yīng)用程序分解為組件。每個(gè)組件都應(yīng)該有一個(gè)定義好的角色,理想情況下您可以進(jìn)行單元測(cè)試。
例如,假設(shè)您想顯示產(chǎn)品列表,那么您應(yīng)該創(chuàng)建一個(gè)產(chǎn)品列表組件。
<Products :list="products" />
在你的應(yīng)用程序中,你會(huì)做類似的事情
data() {
return {
prodcuts: []
}
},
mounted() {
axios.get('/api/products').then(res => {
this.products = res.data
})
}
每當(dāng)您看到“是某物的塊”時(shí),就可以從中創(chuàng)建一個(gè)組件,創(chuàng)建 props 和方法,然后在掛載的鉤子上使用 api 并填充組件。
添加回答
舉報(bào)
0/150
提交
取消