参考 : vue-element-admin
1.项目根目录创建[vue.config.js]文件,填入一下内容
'use strict'
const path = require('path')
function resolve(dir) {
return path.join(__dirname, dir)
}
const port = process.env.port || process.env.npm_config_port || 9527 // dev port
const name = '测试' // page title
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
/**
* You will need to set publicPath if you plan to deploy your site under a sub path,
* for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
* then publicPath should be set to "/bar/".
* In most cases please use '/' !!!
* Detail: https://cli.vuejs.org/config/#publicpath
*/
publicPath: '/',
outputDir: 'dist',
assetsDir: 'static',
lintOnSave: process.env.NODE_ENV === 'development',
productionSourceMap: false,
devServer: {
port: port,
open: true,
overlay: {
warnings: false,
errors: true
},
proxy: {
// 代理test开头的uri
'/test': {
target: 'http://192.168.1.1:8080', // 后端地址
// target: 'localhost:8080/manage', // 原始地址
changeOrigin: true, // 开启代理,在本地创建一个虚拟服务端
pathRewrite: {
'^/test': '/test'
}
}
}
//before: require('./mock/mock-server.js')
},
configureWebpack: {
// provide the app's title in webpack's name field, so that
// it can be accessed in index.html to inject the correct title.
name: name,
resolve: {
alias: {
'@': resolve('src')
}
}
},
chainWebpack(config) {
// it can improve the speed of the first screen, it is recommended to turn on preload
// it can improve the speed of the first screen, it is recommended to turn on preload
config.plugin('preload').tap(() => [
{
rel: 'preload',
// to ignore runtime.js
// https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
include: 'initial'
}
])
// when there are many pages, it will cause too many meaningless requests
config.plugins.delete('prefetch')
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
config
.when(process.env.NODE_ENV !== 'development',
config => {
config
.plugin('ScriptExtHtmlWebpackPlugin')
.after('html')
.use('script-ext-html-webpack-plugin', [{
// `runtime` must same as runtimeChunk name. default is `runtime`
inline: /runtime\..*\.js$/
}])
.end()
config
.optimization.splitChunks({
chunks: 'all',
cacheGroups: {
libs: {
name: 'chunk-libs',
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: 'initial' // only package third parties that are initially dependent
},
elementUI: {
name: 'chunk-elementUI', // split elementUI into a single package
priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
},
commons: {
name: 'chunk-commons',
test: resolve('src/components'), // can customize your rules
minChunks: 3, // minimum common number
priority: 5,
reuseExistingChunk: true
}
}
})
// https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
config.optimization.runtimeChunk('single')
}
)
}
}
2.src下面创建util目录, util目录创建request.js, 内容如下
/*引入axios*/
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
const request = axios.create({
baseURL: '', // 基础路径,将统一的部分全部封装
withCredentials: true // 表示请求可以携带cookie
})
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
// response interceptor
request.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
response => {
const res = response.data
// if the custom code is not 20000, it is judged as an error.
if (res.code !== '0') {
Message({
message: res.message || 'Error',
type: 'error',
duration: 3 * 1000
})
// return Promise.reject(new Error(res.message || 'Error'))
return null
} else {
return res
}
},
error => {
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
//前端采用export.default,在写后端代码时用module.export
export default request
3.src下创建api目录,下面为示例 test1.js
import request from '@/utils/request'
export function add(data) {
return request({
url: '/my-boke',
headers: { 'Content-Type': 'application/json' },
method: 'post',
data
})
}
export function update(data) {
return request({
url: '/my-boke',
headers: { 'Content-Type': 'application/json' },
method: 'put',
data
})
}
export function del(data) {
return request({
url: '/my-boke',
method: 'delete',
params: data
})
}
export function list() {
return request({
url: '/my-boke',
method: 'get'
})
}
4.vue.js调用接口
引入声明
import { add, update, del, list } from '@/api/test1'
调用
add(this.temp).then(() => {
this.list.unshift(this.temp)
this.dialogFormVisible = false
this.$notify({
title: '成功',
message: '创建成功',
type: 'success',
duration: 2000
})
this.getList()
})