vue 模拟数据的方法

2019-09-19  本文已影响0人  阿克兰

1.首先安装

npm install --save json-server

2.在index.html同级目录下,新建一个 JSON 文件db.json,把你的数据放进去
3.在build\webpack.dev.conf.js下配置,如果是用旧版本的手脚架工具初始化的项目,是在build/dev-server.js下配置

/*----------------jsonServer---------*/
/*引入json-server*/
const jsonServer = require('json-server')
/*搭建一个server*/
const apiServer = jsonServer.create()
/*将db.json关联到server*/
const apiRouter = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
apiServer.use(middlewares)
apiServer.use(apiRouter)
/*监听端口*/
apiServer.listen(3000, () => {
  console.log('JSON Server is running')
})

4.浏览器代理设置,在 config/index.js中:

/*代理配置表,在这里可以配置特定的请求代理到对应的API接口*/

proxyTable: {
  '/api': {
    changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
    target: 'http://localhost:3000',// 接口的域名
    pathRewrite: {
      '^/api': ''//后面可以使重写的新路径,一般不做更改
    }
  }

5.npm run dev 运行
6.最后验证一下代理是否成功

http://localhost:3000/#/

7.测试

this.$http.get('/api/db')
  .then((res) => {
    this.newsList = res.data
  }, (err) => {
    console.log(err)
  })
//'/api/db'  如果有问题,直接http://localhost:3000/db
上一篇下一篇

猜你喜欢

热点阅读