本文分享一下在vue3前端項目中請求后端接口獲取數(shù)據(jù)。比較簡單,內容如下:
1、使用axios請求后端接口
首先npm install axios,添加axios依賴,就靠它來請求后端接口了,基本等同于使用jquery發(fā)ajax。
# src/main.js
import axios from 'axios'
import vueAxios from 'vue-axios'
createApp(App).use(ElementPlus).use(vueAxios,axios).mount("#app");
axios是一個獨立的庫,方便調用,這里使用vue-axios,通過this.axios發(fā)起后端請求。后端接口如圖所示:
通過axios獲取到數(shù)據(jù)后賦值到data數(shù)據(jù)即可,頁面引用data數(shù)據(jù)進行展示。
<script>
export default{
data(){
return {
signName: 'star',
users: []
}
},
methods:{
getUsers(){
this.axios.get('/api/getAllUsers')
.then((res)=>{
console.log(JSON.stringify(res.data.records))
this.users = res.data.records
})
.catch(function (error) {
console.log(error);
});
}
},
mounted () {
this.getUsers()
}
}
</script>
2、配置代理
直接向localhost:8787/getAllUsers發(fā)請求會產(chǎn)生跨域問題,通常前端和后端是分開部署的,即使部署在一臺服務器端口也不同,所以存在跨域問題(不考慮將前端dist扔到后端服務器里半分離情況)。
在vue.config.js文件中配置代理(沒有新建一個即可),將本地路徑請求轉發(fā)到目標地址,這樣就可以規(guī)避掉瀏覽器同源策略。同源只是瀏覽器的限制,即便跨域后端還是可以收到請求數(shù)據(jù)的。
module.exports = {
devServer: {
port: 80,
proxy: {
'/api': {
target: 'http://localhost:8787',
secure: true,
changeOrigin: true,
pathRewrite: {
'^/api': '',
},
}
},
},
}
3、頁面table渲染
最后寫一個.vue將請求數(shù)據(jù)展示一下,使用方式和上篇相同,只要有數(shù)據(jù)了頁面展示可以通過第三方組件輕松展示,這里使用element-plus。文章來源:http://www.zghlxwxcb.cn/news/detail-588302.html
<template>
<el-table :data="users" style="width: 100%">
<el-table-column prop="id" label="編號" width="120" />
<el-table-column prop="name" label="姓名" width="120" />
<el-table-column prop="age" label="年齡" width="120" />
<el-table-column prop="city" label="城市" />
</el-table>
</template>
最終效果如下,如果參照本文出現(xiàn)任何與預期不一致的地方,那一定是本文寫錯了,還請參見各個組件官方文檔。文章來源地址http://www.zghlxwxcb.cn/news/detail-588302.html
到了這里,關于寫給后端開發(fā)的『vue3』請求后端接口的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!