VueJS CLI 3.0如何配置mock文件代理
开发Vue的项目时,经常会遇到后台的接口没有完成或者没有稳定,我们都是采用模拟数据的方式去进行开发项目。以便提高我们的开发效率。那如何在前端做一些 mock 数据的处理呢?这里Vue CLI 2.0和Vue CLI 3.0的差别还是挺大的:
比较明显的是,Vue CLI 3.0移除了static文件目录、config、build 等配置目录,vue.config.js 也不是必备的文件。如果需要进行相关配置我们需要在根目录下自己创建 vue.config.js 进行配置。
另外Vue CLI 3.0新增了public 目录,这个目录下的静态资源不会经过 webpack 的处理,会被直接拷贝,所以我们能够直接访问到该目录下的资源。
Vue CLI 2.0目录:如下
Vue CLI 2.0目录
在Vue CLI 2.0,我们的模拟数据会放在static/mock/index.json里,访问以下地址http://localhost:8080/static/mock/index.json (默认8080端口,这里不做介绍),这时在config/index.js文件下配置,
module.exports = { dev: { // Paths fiddler charles assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/api': { target: 'http://localhost:8080', pathRewrite: { '^/api': '/static/mock' } } } } }
Vue CLI 3.0目录:如下
Vue CLI 3.0目录
在Vue CLI 3.0,我们的模拟数据会放在public/mock/index.json里,访问以下地址http://localhost:8080/mock/index.json ,这时我们手动新建vue.config.js文件并做如下配置,
module.exports = { devServer: { host: "localhost", port: 8080, // 端口号 https: false, // https:{type:Boolean} open: true, //配置自动启动浏览器 // proxy: 'http://localhost:4000' // 配置跨域处理,只有一个代理 // 配置多个代理 proxy: { "/api": { target: "http://localhost:8080", // ws: true, // changeOrigin: true, pathRewrite: { '^/api': '/mock' } } } } }
注意:修改webpack配置项的时候,一定要记得重启服务器。
之后在页面里,使用axios请求接口,如下即可获取到数据
axios .get('/api/index.json') .then(res =<{ })
THE END