vue全家桶+Echarts+百度地圖,搭建數據可視化系統(【續】接口篇)

接上篇

vue全家桶+Echarts+百度地圖,搭建數據可視化系統前端

1 前 言

1.1 業務場景

實現數據監控的系統。有線圖、柱狀圖、地圖,並具備定時刷新的功能。vue

1.2 業務分析

上一篇分析的步驟大體有:ios

  1. 系統搭建vue-cli
  2. vuex記錄登陸信息
  3. vue-router路由跳轉
  4. 3個維度的頁面,提取出共用的組件
  5. 各個組件開發
  6. 調節樣式,增長UI
  7. 加入後臺接口數據
  8. 優化顯示
  9. 測試
  10. 上線

上一篇介紹了 1-6 部分。本篇將介紹一下剩下的 7-10 部分。git

😂😂github

主要內容是 <font color=red>對數據的處理方式</font> 和 <font color=red>總體的數據邏輯</font> 。vue-router

望各位看官多提 建議和不足 哈,也但願能本篇能給須要人帶來 啓發。vuex

成品效果圖不方便發,仍是用上一篇,純前端的效果圖吧。vue-cli

2 正 文

2.1 請求處理數據

Vue 中 與後臺交互一般使用的是 axiosnpm

2.1.1 安 裝

npm i axios

也可經過cdn引用json

2.1.2 定 義

新建一個api.js

//  api.js
import axios from 'axios'
const http = axios.create ({
    baseURL : apiurl,       // 鏈接後端地址
    timeout : 1000 * 30,    // 超時時間,單位爲毫秒
    headers : {},          // 請求頭,可添加'Authorization'、'X-Requested-With'、'Accept-Language'、'token'等
})

// 請求攔截
http.interceptors.request.use(config =>{
    // 可添加本身的設置,如修改參數、增長參數、修改headers
    return config
},error =>{
    // 可添加報錯處理
    return Promise.reject(error)
})

// 響應攔截
http.interceptors.response.use(response =>{
    // 可添加處理邏輯
    return response
},error =>{
    return Promise.reject(error)
})

export default http

同時可在main.js中添加一個自定義全局對象,或者可在單獨頁面中引用

// main.js
import http from './api.js'

Vue.prototype.$http = http

2.1.3 使 用

a. get請求

在頁面中處理時

query(){
    this.$http.get('/xxx/xxx?id='+id).then(res =>{
        // 返回的處理
        console.log(res)
        // res 通常包含code data
    },rej =>{
        // 報錯的處理
        console.log(rej)
    })
}

b. post請求

new(){
    this.$http.post('/xxx/xxx',{
        id : '123',
    }).then(res =>{
        // 返回的處理
        console.log(res)
        // res 通常包含code data
    },rej =>{
        // 報錯的處理
        console.log(rej)
    })
}

c. 其餘請求

常用到的還有

put 多用於更新操做

delete 多用於刪除操做

具體要看後臺提供的功能接口方式

d. 多個請求

好比,我在進來頁面後,要同時獲取要2個線形圖、數字、地圖、柱狀圖、表格的數據

通常狀況下,各個數據都是單獨的接口來提供的。這樣咱們就須要至少6個接口。

async query(){
    let that = this
    await axios.all([that.get1(), that.get2(), that.get3()]).then(axios.spread((res1, res2, res3) =>{
        // res1 爲 get1 的返回
        // res2 爲 get2 的返回
        // res3 爲 get3 的返回
    }))
}

get1(){
    return this.$http.get('/xxx/xxx')
}

get2(){
    return this.$http.get('/xxx/xxx')
}

get3(){
    return this.$http.get('/xxx/xxx')
}

2.2 登 錄

功能很簡單,用戶輸入用戶名、密碼、驗證碼,點擊登陸。

2.2.1 獲取uuid

出於對登陸時效以及安全性的考慮。在登陸驗證時,後臺根據 uuid 和經過 uuid 獲取到的驗證碼進行校驗。

這裏列出一些獲取 uuid 的方法。來源於:網絡。

方法一:

getUUID () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
    })
},

方法二:

generateUUID() { 
    var d = new Date().getTime()
    if (window.performance && typeof window.performance.now === "function") { 
        d += performance.now()
    }
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { 
        var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16) 
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
    })
    return uuid
}

方法三:

guid() { 
    function S4() { 
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    } 
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4())
}

方法四:

/*
    指定長度和基數
*/
function uuid2(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],
        i;
    radix = radix || chars.length;

    if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
        var r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
        uuid[14] = '4';
        for (i = 0; i < 36; i++) {
            if (!uuid[i]) {
                r = 0 | Math.random() * 16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }
    return uuid.join('');
}

2.2.2 密碼加密

--input 
type="password" 可以使輸入框中內容隱藏

傳輸時,我使用了md5加密

npm i -S js-md5
import md5 from 'js-md5'

let enCode = md(code)

而後就是調用後臺接口將你的用戶名、密碼、驗證碼發送進行驗證登陸。

2.2.3 存儲登陸信息

使用過 Vue 的童鞋都清楚,使用vuex的時候,進行刷新頁面,store中的數據就會重置。

會防止用戶在刷新頁面後數據沒法獲取的狀況,通常會將數據同時儲存到 sessionStoragelocalStorage

二者區別這裏就不介紹了。

// 儲存session,具體放在哪一個位置根據實際業務
// 我這裏放在了登陸驗證經過以後,固然有不少參數,可以使用對象類型轉成json ----JSON.stringify(info)
sessionStorage.setItem('info', '123')
// store.js

store = {
    state : JSON.parse(sessionStorage.getItem('info')) || {}
}

這樣頁面刷新後,store 會從 sessionStorage 拿到咱們的數據

2.3 業務頁面

業務頁面分了3個維度。

這裏介紹2個維度的實現。

2.3.1 總體邏輯

單獨的組件只處理數據的展現

如線形圖單獨寫在一個組件中

我在須要的頁面中進行引用,傳入數據進行顯示。

  1. 用戶登陸驗證後,儲存業務 IDsession 中,從登陸頁面跳轉到 層級1 頁面。
  2. 進入 層級1 後,created 中增長初始化方法。就是使用了上面介紹的 axios.all
  3. 拿到各數據後,分別渲染到各個組件中。
  4. 初始化完成後,觸發定時刷新開發。
  5. 根據定時器的時間,觸發須要刷新的功能,同上 axios.all 和處理結果。
  6. 點擊層級1中某個數據,記錄層級2須要的 ID2session中,關閉定時刷新,跳轉到 層級2 頁面。
  7. 進入 層級2 後,同層級1,先進行初始化,再進行定時刷新。
  8. 層級3 以及 返回 的邏輯都基本和上面同樣。

下面介紹一些可能會有 疑問 的地方

2.3.2 層級頁面舉例

至關於介紹了一些父子組件的一些處理。

// 層級1.vue
<template>
    <div id="xxx">
        <a-com ref="aRef" :args="argA"/>
        <b-com ref="bRef" :args="argB"/>
    </div>
</template>

<script>
    import Acom from './a.vue'
    import Bcom from './b.vue'
    import store from './store.js'
    
    export default {
        components : {
            'a-com':Acom,
            'b-com':Bcom,
        },
        
        created(){
            //  初始化方法
            this.init()
        },
        
        mounted(){
            //  定時查詢方法
            this.timeq()
        },
        
        data() {
            return {
                //  傳入子組件的數據,可可使用store
                argA : {},
                argB : {},
                
                // 定時開關
                timimg : false,
            }
        },
        
        methods: {
            async init(){
                let id1 = store.state.info.id1
                await this.query(id1)
                this.timimg = true
            },
            
            timeq(){
                //  這裏定義了 5S 刷新一次
                let that = this
                this.timequery = setInterval(() =>{
                    if(timimg){
                        that.querytime(store.state.info.id1)
                    }
                },5000)
            },
            
            async query(id){
                let that = this
                await axios.all([that.get1(id), that.get2(id)]).then(axios.spread((res1, res2) =>{
                    // 數據傳入組件a,觸發組件a的初始化方法
                    that.argA = res1.data
                    that.$refs.aRef.init();
                    
                    // 數據傳入組件b,觸發組件b的初始化方法
                    that.argB = res2.data
                    that.$refs.bRef.init();
                }))
            },
            
            querytime(id){
                //  同 query()  
            },
            
            get1(id){
                return this.$http.get('xxx')    
            },
            
            get2(id){
                return this.$http.get('xxx')
            },
            
            //  跳轉第二層級
            goto2(){
                this.timing = false
                if(this.timequery){
                    clearInterval(this.timequery)
                }
                // replace、push, 也可使用name 
                this.$router.replace('./path2')
            },
        }
    }
</script>

2.3.3 組件頁面舉例

// 若是使用了父組件向子組件傳值的方式,需在子組件的 data 中 定義 props 用於接收

// echarts 初始化
init(){
    // 和上篇介紹 echarts 中定義差很少
    var myChart = this.$echarts.init(document.getElementById("id"),'temp')
    let option = {}
    option = {
        // 吧啦吧啦 一頓操做和配置
        // 可參考上一篇文章,更多參考 官網配置頁面
        myChart.setOption(option, true)
    }
}
這裏有一個須要注意的地方就是

橫向柱狀圖,最下方 是第一條,咱們自定義標題的時候,就要顛倒過來使用。

同時會根據條數自動切換位置,咱們的表頭也須要根據數量進行位置調整。

2.4 測 試

說實話,這方面一直都沒認真寫過。。。

通常業務變更的狀況下,邏輯也會變更頻繁。

但編寫測試代碼仍是很重要的。

Vue 官方推薦的是使用 karmamochachai 等。

感興趣的 能夠 專門去了解學習下

這一大塊不亞於 編寫 業務代碼 😅😅😅

這裏很少介紹了哈。

2.5 打 包

npm run build

可在根目錄中 新建 vue.config.js

官方文檔: https://cli.vuejs.org/zh/config/

//  官方文檔: https://cli.vuejs.org/zh/config/
module.exports = {
    baseUrl: process.env.NODE_ENV === 'production' ? './' : '/',
}

3 後 記

感謝支持。若不足之處,歡迎你們指出,共勉。

若是以爲不錯,記得 點贊,謝謝你們 😂

歡迎關注 個人: 【Github】 【掘 金】 【簡 書】

本文章採用 知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議 進行許可。

出處爲:https://github.com/xrkffgg/Tools

相關文章
相關標籤/搜索