vue3.0實戰電商系統:高解耦式mock 訂單列表查詢(第四天)

章節文章課程簡介:

任何事情都須要時間的沉澱,技術也不例外,今天編寫Vue3.0系列的章節文章,只是但願可以比別人更早的去嚐鮮一些新的技術,畢竟Vue3.0已經Beta版本了,因此里正式版本也不遠了,提早去學習和了解,咱們就會比別人有更多的時間去充分理解Vue3.0的特性,只有當你真正理解一門技術的時候,纔可以正確的斷定它是否合適、是否應該運用到你當前的實際項目當中去。javascript

  • 第一天:淺談vue3.0、初始化項目之:Hello World Vue3.0
  • 次日:Api實戰之:vue-composition 我是api調用工程師
  • 第三天:vue3如何實現邏輯複用
  • 第四天:實戰之:高解耦式mock api的設計與訂單列表查詢
  • 第五天:如何實現代碼優化

今天是第四天:實戰之:高解耦式mock api的設計與訂單列表查詢

上一篇文章有同窗說,不知道我安裝的vue3.0相關的包的版本,因此先貼下package.json,其實都是Vue3.0周邊插件的next版本css

{
 "name": "vue_3.0",
 "version": "1.0.0",
 "description": "vue3.0",
 "main": "index.js",
 "scripts": {
   "dev": "webpack-dev-server --config ./config/webpack.config.js",
 },
 "keywords": [],
 "author": "虎克小哥哥",
 "license": "ISC",
 "dependencies": {
   "@vue/compiler-sfc": "^3.0.0-beta.5",
   "css-loader": "^3.5.3",
   "file-loader": "^6.0.0",
   "html-webpack-plugin": "^4.3.0",
   "mini-css-extract-plugin": "^0.9.0",
   "style-loader": "^1.2.1",
   "vue": "^3.0.0-beta.5",
   "vue-loader": "^16.0.0-alpha.3",
   "vue-router": "4.0.0-alpha.10",
   "webpack": "^4.43.0",
   "webpack-cli": "^3.3.11",
   "webpack-dev-server": "^3.10.3"
 }
}
複製代碼

入口文件src/main.jshtml

import{ createApp } from "vue";
import App from "./App.vue";
import router from './router';
const app=createApp(App);
app.use(router);
app.mount("#root")
複製代碼

根視圖:src/App.vuevue

<template>
    <router-view></router-view>
</template>
複製代碼

路由:src/router/index.jsjava

import { createRouter, createWebHashHistory } from 'vue-router';
import orderList from '../views/order/orderList.vue'
const routes = [
  {path: '/', redirect: '/order-list'},
  {path: '/order-list', component: orderList}
]

// 和react套路同樣
export default createRouter({
  //createWebHashHistory createWebHistory()兩種模式根據須要選擇
  history: createWebHashHistory(),
  routes
})
複製代碼

列表首頁(粗糙的頁面,不要噴我哈) /src/views/order/orderList.vuereact

<template>
  <section>
    <!-- 頭部from部分 -->
    <div class="box-form">
      <!-- 輸入框更新自動節流查詢 -->
      <input type="text" v-model="userName">
    </div>
    <!-- 粗糙的table部分 -->
    <div class="box-table">
      <table>
        <thead>
          <tr>
            <th>訂單編號</th>
            <th>商品名稱</th>
            <th>下單時間</th>
            <th>訂單狀態</th>
            <th>商品價格</th>
            <th>續費時長</th>
            <th>用戶名稱</th>
            <th>用戶性別</th>
            <th>用戶地址</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item,index) in page.data" :key="index">
            <td>{{item.orderCode}}</td>
            <td>{{item.userName}}</td>
            <td>{{item.age}}</td>
            <td>{{item.city}}</td>
            <td>{{stateObj[item.state||'0']}}</td>
            <td>{{item.title}}</td>
            <td>{{item.price}}</td>
            <td>{{item.createtime}}</td>
            <td>{{item.timeNum}}</td>
          </tr>
        </tbody>
      </table>
      <!-- 分頁部分 -->
      <ul class="box-page">
        <li><a>上一頁</a></li>
        <li v-for="(item,index) in page.pageList" :key="index"><a>{{index+1}}</a>
        </li>
        <li><a>下一頁</a></li>
      </ul>
    </div>
  </section>
</template>

<script> import { ref,onMounted,customRef,watch, onUnmounted } from 'vue'; import user from "../../services/interface/user";//沒配相路徑須要本身配 /**節流 */ function useThrottle(value, delay = 1000) { let timeout return customRef((track, trigger) => { return { get() { track();//必須調用次函數纔會觸發更新 return value }, set(newValue) { clearTimeout(timeout) timeout = setTimeout(() => { value = newValue trigger()//必須調用次函數纔會觸發更新 }, delay) } } }) } export default { setup() { const stateObj=ref({0:"未知訂單",1:"已收款"}); const userName=ref(useThrottle(''));//視圖更新後節流更新 const page=ref({pageList:[],total:0,pageSize:10,pageIndex:1}); //視圖初始化 onMounted(()=>{ //查詢數據源 const onQuery=()=>{ user.getOrderList({pageSize:10,pageIndex:1}).then((res)=>{ page.value={ data:res.list, pageList:new Array(Math.ceil(res.total/res.pageSize)), total:res.total, pageSize:res.pageSize, pageIndex:res.pageIndex } }) } //http請求數據 onQuery(); //監聽某個響應對象  const stop = watch(() => userName.value,(userName, prevUserName) => { console.log("從新查詢數據") onQuery(); } ) }) //視圖銷燬後關閉監聽對象 onUnmounted(()=>{ stop(); }) return { stateObj, userName, page } } }; </script>

<style> body { padding: 50px; color: #42b983; background-color: #282c34; text-align: center; } .box-form{ padding: 20px; } .box-form input{ border: none; padding: 4px; } .box-table{ width: 100%; } .box-table table{ display: inline-table; } .box-page li{ list-style: none; display: inline-block; border: 1px #fff solid; border-radius: 6px; min-width: 32px; padding: 0 6px; color: #fff; cursor: pointer; } table tr>th{ text-align: left; padding: 0px 16px; } tbody>tr>td{ padding: 16px; overflow-wrap: break-word; } </style>

複製代碼

src/mock/user.jswebpack

export default {
  "getOrderList":{
    "mock": true,
    "status": 200,
    "msg": "",
    "data":{
      list:new Array(10).fill({}).map((item,index)=>{
        return {
          orderCode:`SH_${new Date().getTime()}_${index}`,
          title:"掘金會員",
          createtime:"2020-05-03",
          state:1,
          price:19.8,
          timeNum:12,
          userName:"虎克小哥哥",
          age:18",
          city:"上海"
       }
      }),
     total:20,
     pageSize:10,
     pageIndex:1
    }
  },
}

複製代碼

src/mock/mockFactory.jsweb

import user from './user'
export default {
    user
}
複製代碼

src/services/interface/user.jsvue-router

import http from "../http";
// 函數生產
const userFuns = {
  getOrderList: "/api/getOrderList"
};
//生成函數實例
export default Object.assign(
  http.packageNewFuns({funs:userFuns},http.post,"user"),
);
複製代碼

src/services/http.jsjson

import mockFactory from '../mock/mockFactory';
/** * 直接根據空間名稱很函數名稱直接返回mock數據源 * @param {}} namespace * @param {}} funName */
const mockRequest=(namespace,funName,parent)=>{
    return new Promise((resolve)=>{
     //模擬裝個逼
     let time=setTimeout(()=>{
       clearTimeout(time);
       resolve(mockFactory[namespace][funName].data);
     },500)
    })
}
/** * 根據每一個模塊生產函數 * @param {*} option 接口服務對應的實例配置 * @param {*} request 接口服務請求實例 * @param {*} namespace 服務所屬空間名稱(就是scope隔離下) */
const packageNewFuns = (option,request,namespace) => {
    const packageS = {};
    Object.keys(option.funs).forEach((funName) => {
        packageS[funName] = (parent) => {
            //若是是mock接口 
            if(mockFactory[namespace][funName].mock){
                return mockRequest(namespace,funName,parent);
            }else{
              // 真實請求
            }
        };
    });
    return packageS;
};

export default {
    packageNewFuns,
    post
};
複製代碼

其餘webpack部分的代碼,上一篇文章中有,就不貼了

運行命令,啓動服務

yarn dev
複製代碼

完美運行 http://localhost:8081/#/order-list

alt vue3.0

簡易目錄結構

alt vue3.0

第一天:淺談vue3.0、初始化項目之:Hello World Vue3.0

次日:Api實戰之:vue-composition 我是api調用工程師

第三天:vue3.0實戰從0到1實戰電商管理系統

下一篇:第五天:如何實現代碼優化

🎨 原創不易,支持請點贊、轉發和關注我,後續持續更新原創文章,有問題留言給我

相關文章
相關標籤/搜索