VUE vue2.0配置webpack.dev.conf.js加载本地json数据

以饿了么项目为例:

打开webpack.dev.conf.js

在const portfinder = require('portfinder')后加入以下配置

const express = require('express')

const app = express() // 请求server

var appData = require('../data.json') //加载本地数据

var seller = appData.seller //获取对应的数据

var goods = appData.goods

var ratings = appData.ratings

var apiRoutes = express.Router()

app.use('/api', apiRoutes) //通过路由请求数据

 

在devServer: { }中加入以下配置
before(app) {
      app.get('/api/seller', (req, res) => {
        res.json({
          errno: 0,
          data: seller // 接口返回json数据
        })
      }),
      app.get('/api/goods', (req, res) => {
        res.json({
          errno: 0,
          data: goods // 接口返回json数据
        })
      }),
      app.get('/api/ratings', (req, res) => {
        res.json({
          errno: 0,
          data: ratings // 接口返回json数据
        })
      })
    }
  }

使用在main.js 中引入vue-resource插件,并使用它
import VueResource from 'vue-resource'
Vue.use(VueResource)
调用数据
this.$http.get('/api/goods').then(response => {
      console.log(response.body);
      this.goods = response.body.data;
  }, response => {
      console.log(response);
  });

以上是es6的箭头函数写法,es5写法如下
this.$http.get('/api/goods').then(function (response) {
      console.log(response.body);
      this.goods = response.body.data;
  }, function (response) {
      console.log(response);
  });

 

posted @ 2020-07-03 08:54  番茄匠Amy  阅读(339)  评论(0编辑  收藏  举报