vue2模拟数据

1、在webpack.dev.conf.js中,在portfinder后面添加

const portfinder = require('portfinder')

const express = require('express')
// 请求server
const app = express()
// 加载本地数据文件
var appData = require('../db.json')
// 获取本地数据
var newList = appData.newList
// 通过路由请求数据,所有接口相关的都经过api
var apiRouter = express.Router()
app.use('/api', apiRouter)

2、在devServer中加入

 poll: config.dev.poll,
    },
    before(app) {
      app.get('/api/newList', (req, res) => {
        res.json({ newList })
      })
    }

3、使用时

created: function() {
    this.$http.get('/api/newList')
    .then((res) => {
      this.newList = res.data.newList     // 在devServer中结果,又加了一层json,所以.newList
    }, (err) => {
      console.log(err)
    })
  },

4、db.json

{
  "newList": [
    {
    "title": "新闻条目1新闻条目1新闻条目1新闻条目1",
    "url": "http://starcraft.com"
    },
    {
      "title": "新闻条目2新闻条目2新闻条目2新闻条目2",
      "url": "http://warcraft.com"
    },
    {
      "title": "新闻条3新闻条3新闻条3",
      "url": "http://overwatch.com"
    },
    {
      "title": "新闻条4广告发布",
      "url": "http://hearstone.com"
    }
  ]
}

猜你喜欢

转载自blog.csdn.net/snow_small/article/details/79378072