1. 程式人生 > >uni-app 小案例解析

uni-app 小案例解析

效果:

              

   1.Fly官網地址:https://wendux.github.io/dist/#/doc/flyio/readme

    2.專案檔案:

       2.1 網路請求的request.js

//目前沒有針對uni的Fly版本,使用wx版本沒有問題,引入Fly
import Fly from 'flyio/dist/npm/wx'

//建立Fly例項
      const request = new Fly()

//將箭頭函式例項賦值給errorPrompt
//箭頭函式相當於
//function (err) {
//   uni.showToast({
//    title: err.message || 'fetch data error.',
//    icon: 'none'
// })
//}
      const errorPrompt = (err) => {
      uni.showToast({
      title: err.message || 'fetch data error.',
      icon: 'none'
      })
      }

//新增Fly的請求攔截器,可以通過它在請求之前做一些預處理
//請求攔截器中的request物件結構如下:
//{
// baseURL,  //請求的基地址
// body, //請求的引數
//  headers, //自定義的請求頭
// method, // 請求方法
// timeout, //本次請求的超時時間
// url, // 本次請求的地址
//  withCredentials //跨域請求是否傳送第三方cookie
//}
      request.interceptors.request.use((request) => {
      uni.showLoading({
      title: '載入中'
      });
      return request
      })


//新增響應攔截器,響應攔截器會在then/catch處理之前執行
//promise 承諾,承諾需要完成的兩件事,指定承諾需要完成的事,設定承諾是否實現的標準
//resolve和reject是判斷承諾是否實現的兩個函式
//如果請求成功,且response.data呼叫裡有資料,說明承諾已經實現了,呼叫resolve方法
//如果進入了處理錯誤的方法,說明請求被拒絕了,呼叫reject方法
//響應攔截器中的response物件結構如下
//{
//  data, //伺服器返回的資料
//  engine, //請求使用的http engine(見下面文件),瀏覽器中為本次請求的XMLHttpRequest物件
//  headers, //響應頭資訊
//  request  //本次響應對應的請求資訊
//}
      request.interceptors.response.use((response, promise) => {
      uni.hideLoading();
      return promise.resolve(response.data)
      }, (err, promise) => {
      //錯誤走到這裡,隱藏載入中,toast錯誤資訊,處理錯誤
      uni.hideLoading();
      errorPrompt(err)
      return promise.reject(err)
      })



//export用於對外輸出本模組(一個檔案可以理解為一個模組)變數的介面,其他JS檔案就可以通過import命令載入這個模組(檔案)
      export default request

    2.2處理網路請求的store.js

//引入request.js檔案
import request from 'common/request'


//const定義的變數不可以修改,而且必須初始化。
//async,非同步方法用來處理請求網路資料,因為請求網路資料可能耗時,如果同步,則會影響體驗和效能
      const getProducts = async function (page=1) {

      //let是塊級作用域,函式內部使用let定義後,對函式外部無影響。
      //var定義的變數可以修改,如果不初始化會輸出undefined,不會報錯,且變數的作用域是全域性的
      let url = `https://api.beidian.com/mroute.html?method=beidian.h5.shop.product.list&page=${page}&shop_id=682731`;

      console.log(url);
      //使用await是執行順序控制,每執行一個await,程式都會暫停等待await返回值,然後進行下一步
      //只能在async方法裡,使用await
      //呼叫Fly例項的get方法,發起網路請求
      const data = await request.get(url);
      if (data.has_more) {
      return data.shop_products;
      } else {
      return false;
      }
      }


      const search = async function(keywords, page=1) {

      keywords = encodeURI(keywords);
      let url =
      `https://api.beidian.com/mroute.html?method=beidian.search.item.list&keyword=${keywords}&sort=hot&page_size=20&page=${page}`;

      console.log(url);
      const data = await request.get(url);


      if (data.has_more) {
      return data.items;
      } else {
      console.log("沒有資料了!")
      return false;
      }
      }


//每個模組內部,module變數代表當前模組,這個變數是一個物件,它的exports屬性(module.exports={})是對外的介面。載入某個模組,其實是載入該模組的module.exports屬性。
//exports    var exports = module.exports; exports是引用 module.exports的值,而模組匯出的時候,真正匯出的執行是module.exports,而不是exports
      module.exports= {
      getProducts,
      search,
      }

      2.3檢視頁面index.vue

<template>
//flex:1 讓所有彈性盒模型物件的子元素都有相同的長度,且忽略它們內部的內容:
<view style="flex-direction: column; flex: 1;">

<block v-for="(item,index) in productList" :key="index">

<view class="">
<view style="flex-direction: column; flex: 1;">
<view style="height: 750upx;">
<image :src="item.img" mode="" style="width: 100%; height: 100%;"></image>
</view>
<view style="padding-top: 30upx; padding-left: 20upx; padding-right: 20upx; font-size: 30upx; font-weight: bold;">
      {{item.title}}</view>
<view style="padding: 20upx;">
<view>
<view>
           ¥{{item.price}}
</view>
<view style="padding-left: 20upx;">
      {{item.seller_count}}
</view>
</view>
<view class="" style="flex: 1; justify-content: flex-end;">
<view>
<button type="danger" size="mini">購買</button>
</view>
</view>
</view>
</view>
</view>
<view class="" style="background-color: #8F8F94; height: 20upx;"></view>
</block>

</view>
</template>

<script>
   import service from 'service/store.js';
         export default {
      data: {

      productList:[
      ]
      },
      async onLoad() {
      const productList = await service.getProducts(1);
      this.productList=productList;
      console.log(JSON.stringify(productList));
      }
      }
</script>

<style>
   view {
         display: flex;
         flex-direction: row;
         font-size: 28upx;
         }
</style>

 2.4在pages.json中加入底部導航欄實現

"tabBar": {
      "color": "#cdcdcd",
      "selectedColor": "#1296db",
      "borderStyle": "black",
      "backgroundColor": "#ffffff",
      "list": [{
      "pagePath": "pages/home/index",
      "iconPath": "static/tabbar/home.png",
      "selectedIconPath": "static/tabbar/homeHL.png",
      "text": "首頁"
      }, {
      "pagePath": "pages/lab/index",
      "iconPath": "static/tabbar/lab.png",
      "selectedIconPath": "static/tabbar/labHL.png",
      "text": "實驗"
      }, {
      "pagePath": "pages/my/index",
      "iconPath": "static/tabbar/my.png",
      "selectedIconPath": "static/tabbar/myHL.png",
      "text": "關於"
      }]
      },

    2.5加入底部導航欄的頁面也要在pages.json中的pages裡新增

"pages": [ //pages陣列中第一項表示應用啟動頁
      {
      "path": "pages/home/index",
      "style": {
      "navigationBarTitleText": "首頁"
      }
      },
      {
      "path": "pages/my/index",
      "style": {
      "navigationBarTitleText": "關於"
      }
      }, {
      "path": "pages/lab/index",
      "style": {
      "navigationBarTitleText": "實驗"
      }
      }
      ],