vue-cli(vue2.x)配置——axios访问本地模拟的json数据文件

有时候我们没有后台接口请求文件,那么我们可以自己在项目根目录下模拟json数据文件,然后通过请求这个文件来渲染我们的组件。

1、配置build/webpack.dev.conf.js文件

1.1、在const devWebpackConfig = merge(baseWebpackConfig, {...........}这个配置项前面添加:
// 增加express
const express = require('express')
const app = express()
//加载项目根目录下模拟的本地json数据文件
var appData = require('../singerData.json')  //获取本地数据json对象
var dataRoutes = express.Router()
// ’/localdata’是自定义的前缀路径
app.use('/localdata', dataRoutes)  
1.2、在devServer配置项的最前面添加:
//增加路由规则before
before(app) {
      app.get('/localdata/singers', (req, res) => {  //注意这里的路径就是后面axios请求的路径名
        res.json({   //自定义请求返回的对象属性
          code: 0,
          datas: appData
        })
      })
    }

注意:修改了配置文件记得重新编译打包: npm run dev

2、在任意组件中使用axios来请求本地json数据文件

这里为访问本地模拟的json数据,url路径要和配置文件中的路径一致

      this.$ajax({
        method: 'get',
        url: '/localdata/singers' //url路径要和配置文件中的路径一致
      })
      .then(function (res) {
        console.log(res)
      })
      .catch(function (error) {
        console.log(error)
      })

猜你喜欢

转载自blog.csdn.net/m0_38134431/article/details/83786085