样本在我的下载
//使用淘宝镜像
npm install -g cnpm --registry=https://registry.npm.taobao.org
- vue init webpack vue-pc // 创建项目
- cnpm i // 装包
- cnpm i element-ui -D // 安装element
- cnpm install babel-plugin-component -D //element按需引入
- 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 安装拦截
cnpm install axios
src/config/header
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) => {})
}
- 反向代理
proxyTable: {
'/api': { //将http://192.168.1.51:8080/grain印射为/api
target: 'http://192.168.1.51:8080/dididcarapi',//接口域名
// target: 'http://www.91dadi.com/dididcarapi/',//接口域名
changeOrigin: true,//是否跨域
pathRewrite: {
'^/api': ''
}
}
},