vue+element+axios+axios攔截+ajax請求抽離+less專案搭建
阿新 • • 發佈:2018-12-03
- vue init webpack vue-pc
- cnpm i
- cnpm i element-ui -D
- cnpm install babel-plugin-component -D //按需引入
- src/main.js
import './config/element';
- .babelrc
{ "presets": [ [ "env", { "modules": false } ] ], "plugins": [ [ "component", { "libraryName": "element-ui", "styleLibraryName": "theme-chalk" } ] ] }
- src/config/element
import Vue from 'vue'
import { Button, Select } from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(Button)
Vue.use(Select)
- less引入
cnpm install less less-loader -S
- build/webpack/base.conf 配置less
{ test: /\.less$/, loader: "style-loader!css-loader!less-loader", }
- axios 攔截
src/config
import axios from 'axios' //新增請求攔截器 axios.interceptors.request.use(function (config) { // console.log(config); // 獲取token let TOKEN = localStorage.token; // 設定token if (TOKEN) { config.headers['X-ODAPI-Authorization'] = TOKEN; } // 返回配置項 return config; }, function (error) { //請求錯誤時做些事 console.log("請求失敗"); return Promise.reject(error); }); //新增響應攔截器 axios.interceptors.response.use(function (response) { return response.data; /** * 下面是判斷,暫時註釋 */ // if (response['status'] == 200) { // if (response['data']['code'] == 0) { // return response['data']; // } else { // if (response['data'].hasOwnProperty('erron')) { // console.log(response['data']['erron']); // } // return false; // } // } else { // console.log('網路錯誤!'); // } }, function (error) { //請求錯誤時做些事 console.log(error); return Promise.reject(error); })
src/main
// 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'
//按需匯入element
import './config/element';
//axios路由攔截
import './config/header'
//引入axios
import './newword/apiServer';
//匯入全域性變數
import './config/constant';
//引入公共css
import './css/base.css';
//px轉rem
import './config/rem'
//引入vuex
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
- 抽離ajax請求
src/newword/apiServer
// 註冊API
//將API註冊到Vue的原型中
import Vue from 'vue'
import API from './api/index'
Vue.prototype.API = API
src/newword/api/index
import axios from 'axios'
export default {
getserver(data) {
// data是一個物件
return axios.post("api/agricult***********Homer",data)
}
}
使用
server() {
this.API.getserver({
key: this.zkey,
code: this.zcode
}).then((res) => {
console.log(res);
}, (err) => {})
}