1. 程式人生 > >D2admin框架:V-charts統計圖資料動態顯示

D2admin框架:V-charts統計圖資料動態顯示

(個人筆記,可能有不正確之處,還需修改)

框架&資料庫:node.js+D2admin+V-charts+SQL Server

使用Axios

步驟:

1.安裝模組express、mssql,建立後端資料操作檔案server.js

(寫明資料連線資訊,資料庫查詢語句;命名api路由名稱;設定啟動埠,不能與前端一致。)

var express = require('express');
var app = express();
var sql = require('mssql');
var config = {
server: "資料庫IP",//localhost或IP
database: "資料庫名稱",
user: "資料庫使用者",
password: "密碼",
port: 1433,
pool:{
min: 0,
max: 10,
idleTimeoutMillis:3000
},
options: {
encrypt: true
}
};
app.get('/api/user',function(req,res)
{
//允許跨域請求資料
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
sql.connect(config).then(function()
{ 
var sqlser="資料庫查詢語句";
new sql.Request()
.input('input_parameter',sql.Int,1002)
.query(sqlser).then(function(recordset){
console.dir(recordset);
res.json(recordset);
sql.close();//每次使用完畢進行關閉,第二次查詢時才不會顯示有錯誤
}).catch(function(err){
console.log(err);
res.send(err);
sql.close();//每次使用完畢進行關閉,第二次查詢時才不會顯示有錯誤
});
}).catch(function(err){
console.log(err);
res.send(err);
});
});

app.post('api/user',function(req,res){
})
//操作語句
app.delete('api/user/:userId',function(req,res){
})
//操作語句

/**
* 埠設定3000
*/
app.listen(3000,function(){
console.log('app listening on 3000');
});

2.終端啟動api檔案:node server

3.在瀏覽器中輸入http://localhost:3000/路由名稱檢視是否有獲取到json資料。

例如http://localhost:3000/api/user

注意:後端埠不能與前端的啟動埠相同。

4.獲取到json資料後可以根據json資料檔案,在前端統計圖的頁面賦值資料欄位

<script>
export default {
  name: '自定義名稱',
  data () {
    this.chartSettings = {
……
    }
    return {
      chartData: {
        columns: […],
        rows: [
        …
        ]
      },
      options: [
],
      value: ''
    }
  },
    beforeCreate: function () {
     this.$axios.get('http://localhost:3000/api/user')//server檔案的路由
                      .then( res => {
                        console.log("進入了");//可以在頁面除錯檢視是否有輸出
                     this.chartData.rows=[
                      { '日期': '2018年', '案件': res.recordset[0].查詢欄位, '金額': res.recordset[1].查詢欄位},
                      { '日期': '2017年', '案件': res.recordset[0].查詢欄位, '金額': res.recordset[1].查詢欄位},
                      { '日期': '2016年', '案件': res.recordset[0].查詢欄位, '金額': res.recordset[1].查詢欄位}
                     ]
                      })
                      .catch(err => {
                      })
   }
}
</script>