物聯網架構成長之路(36)-Vue前端入門


1. 前言
  物聯網平台,需要有一個類似大屏看板的功能。

  找了一圈,發現阿里已經有對應的DataV產品,但是那個價格有點貴啊。所以找了這個【http://datav.jiaminghi.com/demo/】,這看起來也是挺不錯的。就是需要了解一些前端Vue。說到前端,我之前好久就想入門了。斷斷續續看視頻,寫Demo,寫小程序。但都處於入門階段。而且前端變化太快了。半年沒看,就各種更新了。不過還是遲早要學的。

 

2. 安裝環境
  安裝IDE,這里推薦VSCode,然后安裝Vetur 插件
  Google Chrome 瀏覽器 安裝 Vue.js Devtools 一個Vue的調試工具
  安裝 npm
  請到這里下載 https://nodejs.org/en/download/

 1 #現在npm 倉庫的網絡已經很不錯了,如果還不行,那可以使用cnpm
 2 # 安裝淘寶鏡像
 3 npm install -g cnpm --registry=https://registry.npm.taobao.org
 4 #安裝 vue-cli 全局安裝vue-cli腳手架
 5 npm install -g vue-cli
 6 #查看是否安裝成功
 7 vue -V
 8 #安裝 @vue/cli-init
 9 npm install -g @vue/cli-init
10 #使用vue-cli 創建項目
11 vue init webpack projectName

  測試項目是否正常

1 cd datav
2 npm run dev

 

3.修改部分參數
  1)修改datav/src/router/index.js 在第8行增加mode:'history'

 1 import Vue from 'vue'
 2 import Router from 'vue-router'
 3 import HelloWorld from '@/components/HelloWorld'
 4 
 5 Vue.use(Router)
 6 
 7 export default new Router({
 8   mode: 'history',
 9   routes: [
10     {
11       path: '/',
12       name: 'HelloWorld',
13       component: HelloWorld
14     }
15   ]
16 })

  2)修改datav/config/index.js 第16行,host:'0.0.0.0'

 

4. 安裝部分組件

1 npm install axios
2 npm install vue-axios
3 npm install @jiaminghi/data-view
4 npm install --save-dev mockjs
5 #安裝依賴過程中,如果出現奇奇怪怪的問題,可以刪除 node_modules 然后重新 npm install
6 npm run dev

  最后在datav/package.json 文件里面的依賴為

1   "dependencies": {
2     "@jiaminghi/data-view": "^2.4.5",
3     "axios": "^0.19.0",
4     "vue": "^2.5.2",
5     "vue-axios": "^2.1.5",
6     "vue-router": "^3.0.1"
7   },

  配置axios,在datav/src/main.js 文件配置axios

 1 // The Vue build version to load with the `import` command
 2 // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
 3 import Vue from 'vue'
 4 import App from './App'
 5 import router from './router'
 6 import axios from 'axios'
 7 import VueAxios from 'vue-axios'
 8 import dataV from '@jiaminghi/data-view'
 9 
10 require('./mock/mock.js')
11 require('./http/http.js')
12 
13 Vue.use(VueAxios, axios)
14 Vue.use(dataV)
15 Vue.config.productionTip = false
16 
17 /* eslint-disable no-new */
18 new Vue({
19   el: '#app',
20   router,
21   components: { App },
22   template: '<App/>'
23 })

  配置mockjs
  創建兩個文件分別是 datav/src/http/http.js datav/src/mock/mock.js
  http.js

 1 import axios from 'axios'
 2 
 3 axios.defaults.headers.get['Conetnt-Type'] = 'application/json'
 4 
 5 //請求攔截
 6 axios.interceptors.request.use(
 7   config =>{
 8     const token = localStorage.getItem('userToken');
 9     //Authorization: Bearer AccessToken OAuth2.0認證時,需要從瀏覽器存儲中獲取AccessToken
10     config.headers.Authorization = "Bearer " + "token";
11     return config;
12   },
13   error =>{
14     return Promise.reject(error);
15   }
16 )
17 
18 //響應攔截器
19 axios.interceptors.response.use(
20   response =>{
21     return response;
22   },
23   error =>{
24     return Promise.reject(error);
25   }
26 )
27 
28 export default axios

  mock.js

 1 import Mock from 'mockjs'
 2 
 3 Mock.setup({
 4   timeout: '200 - 400'
 5 })
 6 
 7 function loginFun(param){
 8   console.log(param);
 9   return {
10     "value": 11
11   }
12 }
13 
14 Mock.mock('/login', 'post', loginFun); //虛擬數據

  除了通過mock模擬數據外,還可以通過proxy代理方式。
  兩種方式的區別是,當前后端分離時,前后端定好協議后,雙方同時進行開發,前端可以使用mockjs模擬數據,來繼續前期開發。
  當后端開發完成后,會部署到服務器,此時,前端還需要進行集成和數據調試,這個時候,就需要前端開放時,能請求到服務器的API,但是由於瀏覽器的跨域請求限制,所以需要配置代理。實現本地開發。

  proxyTable方式,在 datav/config/index.js 的 module.exports 里面配置proxyTable

 1     /**
 2      * 代理服務器
 3      */
 4     proxyTable:{
 5       '/api':{
 6         target: 'https://api.wunaozai.com', //目標接口域名
 7         changeOrigin: true, //是否跨域
 8         pathRewrite:{
 9           '^/api': '/' //重寫接口
10         }
11       }
12     },

  沒有后端的同學,可以用這個測試一下:https://api.ly522.com/yiyan

 

5. 開始寫代碼
  修改后HelloWorld.vue 代碼如下

 1 <template>
 2   <div class="hello">
 3     <h1>{{ msg }}</h1>
 4     <h1>{{ mockMsg }}</h1>
 5     <h1>{{ proxyMsg }}</h1>
 6   </div>
 7 </template>
 8 
 9 <script>
10 export default {
11   name: 'HelloWorld',
12   data () {
13     return {
14       msg: 'Welcome to Your Vue.js App',
15       mockMsg: 'mockMsg',
16       proxyMsg: 'proxyMsg'
17     }
18   },
19   mounted() {
20     var that = this;
21     //通過mockjs獲取數據
22     this.axios.post('/login').then((res)=>{
23       console.log(res.data)
24       that.mockMsg = res.data.value;
25     }).catch((err)=>{
26       console.log(err)
27     })
28     //通過proxyTable獲取數據
29     this.axios.get('/api/yan.php?format=json').then((res)=>{
30       console.log(res.data)
31       that.proxyMsg = res.data.text;
32     }).catch((err)=>{
33       console.log(err)
34     })
35   },
36   methods:{
37 
38   }
39 }
40 </script>
41 
42 <!-- Add "scoped" attribute to limit CSS to this component only -->
43 <style scoped>
44 
45 </style>

 

6. 編譯,部署

npm run build

  編譯后,在 datav 目錄下有個dist文件夾,把這個文件夾下的所有文件,部署到服務器,就完成前端開發。
  部署時,可以通過Nginx代理后端和前端,也可以把dist文件夾復制到后端工程里面。

 

7. 運行效果

 

 

 

2020-04-21 11:54:11 更新一些筆記

增加一個request.js

 1 import axios from 'axios'
 2 
 3 const service = axios.create({
 4   baseURL: '/wechat-api',
 5   timeout: 3000
 6 })
 7 
 8 service.defaults.headers.get['Content-Type'] = 'application/json'
 9 service.interceptors.request.use(
10   config => {
11     const jwt = localStorage.getItem('jwt-token')
12     config.headers["jwt-token"] = jwt
13     return config
14   },
15   error => {
16     return Promise.reject(error)
17   }
18 )
19 
20 service.interceptors.response.use(
21   response => {
22     console.log(response)
23   },
24   error => {
25     return Promise.reject(error)
26   }
27 )
28 
29 export default service

增加一個API調用,統一請求

1 import request from '@/http/request'
2 
3 export function demo(data){
4   return request({
5     url: '/error/demo',
6     method: 'post',
7     params: data
8   })
9 }

調用請求

 1 import * as Demo from '@/api/demo'
 2 export default {
 3   name: 'HelloWorld',
 4   data () {
 5   },
 6   created(){
 7     this.demo()
 8   },
 9   methods: {
10     demo() {
11       Demo.demo({a: 1}).then(ret => {
12         console.log(ret)
13       })
14     }
15   }
16 }

 

出現 Invalid Host header

配置 webpack.dev.conf.js 在devServer 下增加 disableHostCheck: true

 


參考資料:
  http://datav.jiaminghi.com/demo/
  https://www.jianshu.com/p/6f8a8568e33a
  https://cli.vuejs.org/zh/guide/

本文地址: https://www.cnblogs.com/wunaozai/p/11663516.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM