前端:Uniapp封裝網(wǎng)絡(luò)請求筆記
uniapp作為開發(fā)移動端的前端框架,目前國內(nèi)是非常流行的,使用HbuilderX開發(fā)工具基于uniapp框架開發(fā)的系統(tǒng)可以方便的轉(zhuǎn)換為小程序、APP等移動端程序,大大降低了移動開發(fā)的成本。網(wǎng)絡(luò)請求更是每個前端項(xiàng)目必備的技術(shù),所以有必要進(jìn)行前端網(wǎng)絡(luò)請求的封裝,今天小編給大家介紹一下,如何基于uniapp實(shí)現(xiàn)網(wǎng)絡(luò)請求的簡單封裝,希望對新手能有所幫助!
1、首先安裝HbuilderX開發(fā)工具創(chuàng)建一個uniapp的項(xiàng)目。
2、common目錄下創(chuàng)建 config,js、request.js 文件
- const BASE_URL="https://qqlykm.cn/api/yan/gc.php";//隨機(jī)查詢古詩接口
request.js
- import {GlobeConfig} from 'config.js'
- export const request = (options)=>{
- return new Promise((resolve, reject)=>{
- // 封裝主體:網(wǎng)絡(luò)請求
- uni.request({
- url: "/api"+options.url,
- data: options.data || {},
- // 默認(rèn)值GET,如果有需要改動,在options中設(shè)定其他的method值
- method: options.method || 'GET',
- success: (res) => {
- console.log(res.data); // 控制臺顯示數(shù)據(jù)信息
- resolve(res)
- },
- fail: (err) =>{
- // 頁面中彈框顯示失敗
- uni.showToast({
- title: '請求接口失敗'
- })
- // 返回錯誤消息
- reject(err)
- },
- catch:(e)=>{
- console.log(e);
- }
- })
- }
- )
- }
- // https://qqlykm.cn/api/yan/gc.php 測試接口
- {"code":"200","msg":"success" ,
- "data":
- {"Poetry":"千人之諾諾,不如一士之諤諤。",
- "Poet":"null",
- "Poem_title":"史記·商君列傳"}
- }
3、main.js 導(dǎo)入封裝的網(wǎng)絡(luò)請求
- //導(dǎo)入封裝的網(wǎng)絡(luò)請求
- import {request} from 'common/request.js'
- Vue.prototype.$request = request
4、新建測試 demo.vue
- <template>
- <view class="content">
- <view class="article-meta">
- <text class="">{{Poem_title}}</text>
- </view>
- <view>
- <text class="">作者:{{Poet}}</text>
- </view>
- <view class="article-content">
- <view>{{Poetry}}</view>
- </view>
- </view>
- </template>
- <script>
- export default {
- data() {
- return {
- Poem_title: "",
- Poet: "",
- Poetry: ""
- }
- },
- onLoad() {
- this.initData();
- },
- methods: {
- async initData() {
- debugger;
- const res = await this.$request({
- url: '', //請求的url默認(rèn)可以寫在配置文件里面
- data: {
- // 接口的請求參數(shù),可能為空
- }
- })
- // 給頁面的數(shù)據(jù)賦值
- if (res.data.msg == "success") {
- this.Poem_title = res.data.data.Poem_title;
- this.Poet = res.data.data.Poet=="null" ? "佚名": res.data.data.Poet;
- this.Poetry = res.data.data.Poetry;
- }
- }
- }
- }
- </script>
- <style lang="scss" scoped>
- </style>
運(yùn)行頁面
個人博客網(wǎng)站:https://programmerblog.xyz
本文轉(zhuǎn)載自微信公眾號「IT技術(shù)分享社區(qū)」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系IT技術(shù)分享社區(qū)公眾號。