npm install axios --save
npm install ant-design-vue --save//引入組件
npm install moment --save//引入日期格式
**
## main.js
**
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import request from './utils/request'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/antd.css'
Vue.prototype.$post = request.post
Vue.prototype.$get = request.get
Vue.config.productionTip = false
Vue.use(Antd)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
src下新建目錄utils,
在utils新建兩個文件,request.js和localstorage.js
## request.js
import axios from 'axios'
import { message, Modal, notification } from 'ant-design-vue'
import moment from 'moment'
// import store from '../store'
import db from './localstorage'
moment.locale('zh-cn')
var baseURL = 'http://114.110.110.110:8080'
function myfun () {
return baseURL
}
export { //很關鍵
myfun
}
// 統一配置
let FEBS_REQUEST = axios.create({
baseURL: baseURL,
responseType: 'json',
validateStatus (status) {
// 200 外的狀態碼都認定爲失敗
return status === 200
}
})
// 攔截請求
FEBS_REQUEST.interceptors.request.use((config) => {
// let expireTime = store.state.account.expireTime
// let now = moment().format('YYYYMMDDHHmmss')
// 讓token早10秒種過期,提升“請重新登錄”彈窗體驗
// if (now - expireTime >= -10) {
// db.clear()
// location.reload()
// Modal.error({
// title: '登錄已過期',
// content: '很抱歉,登錄已過期,請重新登錄',
// okText: '重新登錄',
// mask: false,
// onOk: () => {
// return new Promise((resolve, reject) => {
// db.clear()
// location.reload()
// })
// }
// })
// }
// 有 token就帶上
// if (store.state.account.token) {
// config.headers.Authentication = store.state.account.token
// }
return config
}, (error) => {
return Promise.reject(error)
})
// 攔截響應
FEBS_REQUEST.interceptors.response.use((config) => {
return config
}, (error) => {
if (error.response) {
let errorMessage = error.response.data === null ? '系統內部異常' : error.response.data.message
switch (error.response.status) {
case 404:
notification.error({
message: '系統提示',
description: '很抱歉,資源未找到',
duration: 4
})
// db.clear()
// location.reload()
break
case 403:
case 401:
notification.warn({
message: '系統提示',
description: '很抱歉,您無法訪問該資源,可能是因爲沒有相應權限或者登錄已失效',
duration: 4
})
setTimeout(() => {
db.clear()
location.reload()
}, 600)
break
default:
notification.error({
message: '系統提示',
description: errorMessage,
duration: 4
})
break
}
}
return Promise.reject(error)
})
const request = {
post (url, params) {
return FEBS_REQUEST.post(url, params, {
transformRequest: [(params) => {
let result = ''
Object.keys(params).forEach((key) => {
if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
}
})
return result
}],
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
},
put (url, params) {
return FEBS_REQUEST.put(url, params, {
transformRequest: [(params) => {
let result = ''
Object.keys(params).forEach((key) => {
if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
}
})
return result
}],
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
},
get (url, params) {
let _params
if (Object.is(params, undefined)) {
_params = ''
} else {
_params = '?'
for (let key in params) {
if (params.hasOwnProperty(key) && params[key] !== null) {
_params += `${key}=${params[key]}&`
}
}
}
return FEBS_REQUEST.get(`${url}${_params}`)
},
delete (url, params) {
let _params
if (Object.is(params, undefined)) {
_params = ''
} else {
_params = '?'
for (let key in params) {
if (params.hasOwnProperty(key) && params[key] !== null) {
_params += `${key}=${params[key]}&`
}
}
}
return FEBS_REQUEST.delete(`${url}${_params}`)
},
export (url, params = {}) {
message.loading('導出數據中')
return FEBS_REQUEST.post(url, params, {
transformRequest: [(params) => {
let result = ''
Object.keys(params).forEach((key) => {
if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
}
})
return result
}],
responseType: 'blob'
}).then((r) => {
console.log('導出succ r:', r)
const content = r.data
const blob = new Blob([content])
const fileName = `${new Date().getTime()}_導出結果.xlsx`
if ('download' in document.createElement('a')) {
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href)
document.body.removeChild(elink)
} else {
navigator.msSaveBlob(blob, fileName)
}
}).catch((r) => {
console.error(r)
message.error('導出失敗')
})
},
export2 (url, params = {}) {
message.loading('導出數據中')
return FEBS_REQUEST.post(url, params, {
transformRequest: [(params) => {
let result = ''
Object.keys(params).forEach((key) => {
if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
}
})
return result
}],
responseType: 'blob'
}).then((r) => {
console.log('導出succ r:', r)
const content = r.data
const blob = new Blob([content])
const fileName = '設備安裝信息表_導出模板.xlsx'
if ('download' in document.createElement('a')) {
const elink = document.createElement('a')
elink.download = fileName
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href)
document.body.removeChild(elink)
} else {
navigator.msSaveBlob(blob, fileName)
}
}).catch((r) => {
console.error(r)
message.error('導出失敗')
})
},
download (url, params, filename) {
message.loading('文件傳輸中')
return FEBS_REQUEST.post(url, params, {
transformRequest: [(params) => {
let result = ''
Object.keys(params).forEach((key) => {
if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
}
})
return result
}],
responseType: 'blob'
}).then((r) => {
const content = r.data
const blob = new Blob([content])
if ('download' in document.createElement('a')) {
const elink = document.createElement('a')
elink.download = filename
elink.style.display = 'none'
elink.href = URL.createObjectURL(blob)
document.body.appendChild(elink)
elink.click()
URL.revokeObjectURL(elink.href)
document.body.removeChild(elink)
} else {
navigator.msSaveBlob(blob, filename)
}
}).catch((r) => {
console.error(r)
message.error('下載失敗')
})
},
upload (url, params) {
return FEBS_REQUEST.post(url, params, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
}
export default request
# localstroage.js
let db = {
save (key, value) {
localStorage.setItem(key, JSON.stringify(value))
},
get (key, defaultValue = {}) {
return JSON.parse(localStorage.getItem(key)) || defaultValue
},
remove (key) {
localStorage.removeItem(key)
},
clear () {
localStorage.clear()
}
}
export default db
**
## 組件調用
**
<template>
<div class="container">
<input type="text" v-model="username">
<input type="password" v-model="password">
<button @click="sub">提交</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
username:'',
password:'',
msg: 'Welcome to Your Vue.js App'
}
},
mounted(){
},
methods: {
sub() {
this.$post("login", {
username: this.username,
password: this.password
}).then(r => {
console.log(r);
})
},
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
font-weight: normal;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>