四、vue-router 組件跳轉以及 axios 前後對接

vue-router 組件跳轉

  上篇已完成基本的登錄功能,現在採用 ElementUI 組件庫完善 Main.vue 主頁以及表單組件,並通過 axios 完成前後對接。

1 Container 佈局容器

  打開 Element UI 官網,找到 Container 佈局容器,然後將代碼黏貼進 Main.vue 的 div 標籤內。
.在這裏插入圖片描述
  然後根據需要我們可以去除一部分,去除後的代碼如下:

<template>
  <div>
    <el-container style="height: 100%; border: 1px solid #eee">
      <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
        <el-menu :default-openeds="['1','2','3','4']">
          <el-menu-item>
            <template slot="title"><i class="el-icon-s-home" ></i>主頁
              <router-link to="/"  style="text-decoration-line: none"> </router-link>
            </template>
          </el-menu-item>
          <el-submenu index="1">
            <template slot="title"><i class="el-icon-tickets"></i>違章信息</template>
              <el-menu-item index="1-1">
                <router-link to="#"  style="text-decoration-line: none">違章記錄</router-link>
              </el-menu-item>
          </el-submenu>
          <el-submenu index="2">
            <template slot="title"><i class="el-icon-shopping-bag-2"></i>訂單管理</template>
            <el-menu-item index="2-1">訂單列表</el-menu-item>
            <el-menu-item index="2-2">選項2</el-menu-item>
            <el-menu-item index="2-3">選項3</el-menu-item>
          </el-submenu>
          <el-submenu index="3">
            <template slot="title"><i class="el-icon-user"></i>用戶管理</template>
              <el-menu-item index="3-1">用戶列表</el-menu-item>
              <el-menu-item index="3-2">新增用戶</el-menu-item>
              <el-menu-item index="3-3">選項3</el-menu-item>
          </el-submenu>
          <el-submenu index="4">
              <template slot="title"><i class="el-icon-setting"></i>系統設置</template>
              <el-menu-item index="4-1">數據源設置</el-menu-item>
              <el-menu-item index="4-2">郵件設置</el-menu-item>
              <el-menu-item index="4-3">選項3</el-menu-item>
          </el-submenu>
        </el-menu>
      </el-aside>

      <el-container>
        <el-header style="text-align: right; font-size: 12px">
          <el-dropdown>
            <i class="el-icon-setting" style="margin-right: 15px"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>個人中心</el-dropdown-item>
              <el-dropdown-item>
                <router-link to="/login" style="text-decoration-line: none">退出</router-link>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <span>PkyShare</span>
        </el-header>
      </el-container>
    </el-container>
  </div>
</template>

<script>
  export default {
      name : "Main",
  }
</script>
<style>
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

</style>

router-link to="/login" 爲路由跳轉,這裏跳回登錄頁。

  效果如下:
在這裏插入圖片描述

2 卡片和表格等組件

  在 components 文件夾下新增 QueryRecord.vue 組件,並加入卡片與表格,詳細請查看 tablel

<template>
  <div>
  	查詢記錄
  </div>
</template>

<script>
    export default {
        name: "records"
    }
</script>

<style>

</style>

  修改 index.js 路由

import Vue from 'vue'
import Router from 'vue-router'
//異步加載組件
const Login =() => import('../views/login') // 登錄
const Main =() => import('../views/main') // 主頁導航
const Records =() => import('../components/QueryRecord') // 違章記錄

Vue.use(Router);

export default new Router({
  routes:[
    {
      path:'/login',
      name:'login',
      component:Login
    },
    {
      path:'/',
      name:'main',
      component:Main,
      children: [
        {
          path: '/records',
          name:'records',
          component:Records
        }
      ]
    },
  ]
})

:const 爲異步加載,這樣提高用戶體驗。children 爲嵌套路由,使用它可以在當前父組件下路由到子組件,若不使用,則會跳轉到全新的組件頁面。

   修改 Main.vue,在違章記錄選項中綁定路由,並在第二個 el-container 標籤內添加路由的展示位置

  • 路由綁定
<router-link to="/records" style="text-decoration-line: none">違章記錄</router-link>
  • 子路由的展示位置
 <!--   各組件展示  -->
 <el-main>
 <!--<router-link> 就是定義頁面中點擊的部分,<router-view> 定義顯示部分,就是點擊後,區配的內容顯示在什麼地方,會被匹配到的組件替換掉-->
   <router-view></router-view>
 </el-main>
  • 在組件庫裏找到對應的卡片與表格等組件,通過自己需要把相應組件放入 QueryRecord.vue 的 div 標籤內,以下是完整的 QueryRecord.vue 示例代碼:
<template>
  <div>
    <el-card class="box-card" style="width: 100%" v-show="isShow">
      <div slot="header" class="clearfix">
        <span>高級搜索</span>
      </div>
      <div>
        <el-input style="width: 200px; margin: 3px"
                  placeholder="請輸入查詢記錄ID..."
                  v-model="recordId"
                  clearable>
        </el-input >
        <el-input style="width: 200px; margin: 3px"
                  placeholder="請輸入車牌號..."
                  v-model="carNum"
                  clearable>
        </el-input>
        <el-date-picker
          v-model="timeFrame"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="請選擇開始時間..."
          end-placeholder="請選擇結束時間..."
          :default-time="['12:00:00']">
        </el-date-picker>
        <el-date-picker
          v-model="queryMonth"
          format="yyyy-MM"
          value-format="yyyyMM"
          type="month"
          placeholder="請選擇查詢月份...">
        </el-date-picker>
        <el-input style="width: 200px; margin: 3px"
                  placeholder="請輸入查詢結果信息..."
                  v-model="queryResultInfo"
                  clearable>
        </el-input>
        <el-input style="width: 200px; margin: 3px"
                  placeholder="請輸入查詢地區..."
                  v-model="area"
                  clearable>
        </el-input>
        <el-input style="width: 200px; margin: 3px"
                  placeholder="請輸入用戶名..."
                  v-model="username"
                  clearable>
        </el-input>
        <el-button type="primary" @click="search()" icon="el-icon-search">搜索</el-button>
      </div>
    </el-card>
    <el-card class="box-card" style="width: 100%">
      <div slot="header" class="clearfix">
        <span>違章記錄</span>
      </div>
      <div>
        <el-input style="width: 200px; margin: 3px"
          placeholder="請輸入車牌號..."
          v-model="carNum"
          clearable>
        </el-input>
        <el-input style="width: 200px; margin: 3px"
          placeholder="請輸入查詢地區..."
          v-model="area"
          clearable>
        </el-input>
        <el-input style="width: 200px; margin: 3px"
          placeholder="請輸入用戶名..."
          v-model="username"
          clearable>
        </el-input>
        <el-button type="primary" @click="search()" icon="el-icon-search">搜索</el-button>
        <el-button type="primary" @click="advancedSearch()" icon="el-icon-search">高級搜索</el-button>
      </div>
      <div style="margin-top: 10px">
        <el-table
          :data="tableData"
          height="650"
          style="width: 100%"
          :row-class-name="tableRowClassName">
          <el-table-column
            prop="recordId"
            sortable
            label="查詢記錄ID"
            width="180">
          </el-table-column>
          <el-table-column
            prop="carNum"
            width="100"
            label="車牌號">
          </el-table-column>
          <el-table-column
            prop="eng"
            width="120"
            label="發動機號">
          </el-table-column>
          <el-table-column
            prop="vin"
            width="120"
            label="車架號">
          </el-table-column>
          <el-table-column
            prop="carType"
            label="車型">
          </el-table-column>
          <el-table-column
            prop="queryDate"
            width="170"
            label="查詢時間">
          </el-table-column>
          <el-table-column
            prop="queryMonth"
            label="查詢月份">
          </el-table-column>
          <el-table-column
            prop="queryType"
            label="查詢類型">
          </el-table-column>
          <el-table-column
            prop="queryResult"
            label="查詢結果">
          </el-table-column>
          <el-table-column
            prop="queryResultInfo"
            width="290"
            label="結果信息">
          </el-table-column>
          <el-table-column
            prop="queryTime"
            label="耗時">
          </el-table-column>
          <el-table-column
            prop="ipAddress"
            width="150"
            label="IP">
          </el-table-column>
          <el-table-column
            prop="area"
            label="地區">
          </el-table-column>
          <el-table-column
            prop="datasource"
            label="數據源">
          </el-table-column>
          <el-table-column
            prop="username"
            label="用戶名">
          </el-table-column>
          <el-table-column
            prop="remark"
            width="250"
            label="說明">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="100">
            <template slot-scope="scope">
              <el-button @click="" type="text" size="small">詳情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        style="text-align: center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[100, 150, 200]"
        :page-size="pagesize"
        layout="sizes, prev, pager, next">
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
    export default {
        name: "records",
        data() {
            return {
                isShow: false, // 是否展示
                currentPage:1, //初始頁
                pagesize:100,    //    每頁的數據
                recordId:'', // 查詢記錄ID
                carNum: '', // 車牌號
                timeFrame: '', // 查詢時間範圍
                queryMonth: '', // 查詢月份
                queryResultInfo: '', // 查詢結果信息
                area: '', // 查詢地區
                username: '', // 用戶名
                tableData: [{
                    recordId: '406120545357135871',
                    carNum: '粵123456',
                    eng: '123456',
                    vin: '123456',
                    carType: '02',
                    queryDate: '2019-10-10 15:25:35',
                    queryMonth: '201910',
                    queryType: 0,
                    queryResult: 0,
                    queryResultInfo: 'totalScore:18,totalMoney:2060,count:17',
                    queryTime: '2243',
                    ipAddress: '255.255.255.255',
                    datasource: 'YUE_6',
                    area: '粵',
                    username: '王小虎',
                    remark: '查詢成功'
                },{
                    recordId: '406120545357135872',
                    carNum: '粵123456',
                    eng: '123456',
                    vin: '123456',
                    carType: '02',
                    queryDate: '2019-10-10 15:25:35',
                    queryMonth: '201910',
                    queryType: 0,
                    queryResult: 0,
                    queryResultInfo: 'totalScore:18,totalMoney:2060,count:17',
                    queryTime: '2243',
                    ipAddress: '255.255.255.255',
                    datasource: 'YUE_6',
                    area: '粵',
                    username: '王小虎',
                    remark: '查詢成功'
                },{
                    recordId: '406120545357135873',
                    carNum: '粵123456',
                    eng: '123456',
                    vin: '123456',
                    carType: '02',
                    queryDate: '2019-10-10 15:25:35',
                    queryMonth: '201910',
                    queryType: 0,
                    queryResult: 0,
                    queryResultInfo: 'totalScore:18,totalMoney:2060,count:17',
                    queryTime: '2243',
                    ipAddress: '255.255.255.255',
                    datasource: 'YUE_6',
                    area: '粵',
                    username: '王小虎',
                    remark: '查詢成功'
                },{
                    recordId: '406120545357135874',
                    carNum: '粵123456',
                    eng: '123456',
                    vin: '123456',
                    carType: '02',
                    queryDate: '2019-10-10 15:25:35',
                    queryMonth: '201910',
                    queryType: 0,
                    queryResult: 0,
                    queryResultInfo: 'totalScore:18,totalMoney:2060,count:17',
                    queryTime: '2243',
                    ipAddress: '255.255.255.255',
                    datasource: 'YUE_6',
                    area: '粵',
                    username: '王小虎',
                    remark: '查詢成功'
                },{
                    recordId: '406120545357135875',
                    carNum: '粵123456',
                    eng: '123456',
                    vin: '123456',
                    carType: '02',
                    queryDate: '2019-10-10 15:25:35',
                    queryMonth: '201910',
                    queryType: 0,
                    queryResult: 0,
                    queryResultInfo: 'totalScore:18,totalMoney:2060,count:17',
                    queryTime: '2243',
                    ipAddress: '255.255.255.255',
                    datasource: 'YUE_6',
                    area: '粵',
                    username: '王小虎',
                    remark: '查詢成功'
                }]
            }
        },
        methods: {
            // 初始頁currentPage、初始每頁數據數pagesize和數據data
            handleSizeChange: function (size) {
                this.pagesize = size;
                this.handleList()
            },
            handleCurrentChange: function (currentPage) {
                this.currentPage = currentPage;
                this.handleList()
            },
            handleList() {
                //發送請求
            },
            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            // 普通搜索
            search: function() {
                this.isShow = false
                console.log('timeFrame:' + this.timeFrame)
                console.log('queryMonth:' + this.queryMonth)
                console.log('currentPage:' + this.currentPage)
                console.log('pageSize:' + this.pagesize)
            },
            // 高級搜索
            advancedSearch: function () {
                if(this.isShow == true) {
                    this.isShow = false
                }
                else {
                    this.isShow = true
                }
                console.log("isShow:" + this.isShow)
            }
        }
    }
</script>

<style>
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 480px;
  }
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

</style>

:最好不要複製我的代碼,應該一個組件一個組件地嘗試才能更好地理解。

  • 效果如下:
    在這裏插入圖片描述
    在這裏插入圖片描述

3 axios 請求

  以上表格數據是死數據,並沒有實現前後交互,下面通過 axios 進行發送請求。axios 中文文檔

  Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中,主要是用於向後臺發起請求的,還有在請求中做更多是可控功能。

  • 安裝 axios 插件
npm install axios
  • 在 api 文件夾下新增 queryRcords.js 文件

  具體格式根據 api 文檔進行書寫,我這是 get 請求

import axios from 'axios';

let base = 'http://localhost:9096/api/v1/weizhangurl

// 分頁
export const records = (pageNum, pageSize) => {
  return axios.get(`${base}/records/page/${pageNum}/${pageSize}`);
}
  • 修改 QueryRecord.vue,以下只修改 js 代碼
<script>
    import {records} from "../api/queryRcords"
    export default {
        name: "records",
        data() {
            return {
                isShow: false, // 是否展示
                currentPage:1, //初始頁
                pagesize:100,    //    每頁的數據
                recordId:'', // 查詢記錄ID
                carNum: '', // 車牌號
                eng: '', //
                vin: '', //
                carType: '', //
                queryDate: '', //
                timeFrame: '', // 查詢時間範圍
                queryMonth: '', // 查詢月份
                queryType: '',
                queryResult: '',
                queryResultInfo: '', // 查詢結果信息
                queryTime: '',
                ipAddress: '',
                datasource: '',
                area: '',
                username: '',
                remark: '',
                tableData: []
            }
        },
        // 頁面加載時執行
        created: function() {
            this.handleList()
        },
        methods: {
            // 初始頁currentPage、初始每頁數據數pagesize和數據data
            handleSizeChange: function (size) {
                this.pagesize = size;
                this.handleList()
            },
            handleCurrentChange: function (currentPage) {
                this.currentPage = currentPage;
                this.handleList()
            },
            handleList() {
                //發送請求
                records(this.currentPage, this.pagesize).then(res => {
                    this.tableData = []
                    for (let data of res.data.data) {
                        this.tableData.push(data)
                    }
                })
            },
            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            // 普通搜索
            search: function() {
                this.isShow = false
                this.handleList()
            },
            // 高級搜索
            advancedSearch: function () {
                if(this.isShow == true) {
                    this.isShow = false
                }
                else {
                    this.isShow = true
                }
                console.log("isShow:" + this.isShow)
            }
        }
    }
</script>

注意:需要根據返回的 json 格式才能放入表格數據,我接收的格式如下:

{
    "code": 20000,
    "count": 1045,
    "title": "請求成功",
    "data": [
        {
            "recordId": 406825828807081984,
            "carNum": "遼ACS900",
            "eng": "******",
            "vin": "*******",
            "carType": "01",
            "queryDate": "2019-11-28 15:00:36",
            "queryMonth": 201911,
            "queryType": 0,
            "queryResult": 1,
            "queryResultInfo": "請求超時",
            "queryTime": 19287,
            "ipAddress": "255.255.255.255",
            "area": "遼",
            "datasource": "LIAO_1",
            "username": "****",
            "remark": "請求超時或失敗"
        }
   ]
}
  • 效果
    在這裏插入圖片描述

至此,查詢記錄列表以基本完成,接下來會進一步完善登陸、攔截等相關功能,盡請期待!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章