0x00 環境
brew install node
# node 中自帶 npm 命令
npm install -g axios
npm install -g vue-cli
npm install -g webpack
npm install -g element-ui
0x01 項目創建
vue init webpack demo
0x02 axios 配置
參考: https://www.cnblogs.com/qianxiaox/p/14025708.html
可以進行一些全局axios配置, 這裏的用法相當於創建一個全局的 http 客戶端實例, 然後在各模塊頁裏, 直接引用, 並執行相應方法.
當然, 可以進一步封裝, 把業務請求整合到一個獨立的js裏.
// main.js 直接添加配置信息
import axios from 'axios'
const service = axios.create({
baseURL: '/api',
withCredentials: true,
timeout: 5000,
// headers: {
// get: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// },
// post: {
// 'Content-Type': 'application/json;charset=utf-8'
// }
// },
validateStatus: function () {
return true
},
transformResponse: [
function (data) {
if (typeof data === 'string' && data.startsWith('{')){
data = JSON.parse(data)
}
return data
}
]
})
export default service
然後在具體頁面中, 可以參考如下寫法:
<script>
import service from "../main";
export default {
name: "Menu",
data() {
return {
msg: "Nice"
}
},
methods: {
test() {
service.get('/test')
.then(value => {
console.log(value.data)
this.msg = value.data
})
}
}
}
</script>
0x03 路由轉發
做爲前後端分離開發模式, 肯定會遇到跨域問題, 可以採用下面的方法進行解決:
在項目文件 config/index.js
中, 配置自定義路由轉發:
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://localhost:9000',
changeOrigin: true,
pathRewrite: {
'^/api': '/api'
}
}
},
上面的功能是: 在web前端發的請求, 直接轉換爲向另一個後端服務發請求, 同時支持 uri 前綴置換, 這裏的例子意思是沒有置換, 相當於只改變了服務端口.
0x04 ElementUI 引入
爲了方便使用好看的UI組件, 可以在 main.js
中 添加下面的代碼:
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
組件用法參考: https://element.eleme.cn/#/zh-CN/component/button
0x05 效果圖
<template>
<div>
{{ msg }}
<el-input v-model="msg" placeholder="輸入用戶名..."/>
<el-button type="success" @click.native="test">登錄加載</el-button>
</div>
</template>
<script>
import service from "../main";
export default {
name: "Menu",
data() {
return {
msg: "test"
}
},
methods: {
test() {
service.get('/test')
.then(value => {
console.log(value.data)
this.msg = value.data
})
}
}
}
</script>
<style scoped>
</style>
輸出效果圖:
好了, 這樣就可以最基礎的頁面功能開發了.