其他分享
首页 > 其他分享> > vue mookjs数据

vue mookjs数据

作者:互联网

1.

# 使用axios发送ajax
cnpm install axios --save
# 使用mockjs产生随机数据
cnpm install mockjs --save-dev

2.

报错BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modu
npm install node-polyfill-webpack-plugin
vue.config.js修改

const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
configureWebpack: {
plugins: [new NodePolyfillPlugin()],
}

3.

报错fs模块找不到
package.json添加

"browser": {
"fs": false,
"path": false,
"os": false
}

4.常用的vue.config.js before参数报错

换成这样,用onBeforeSetupMiddleware

  devServer: {
    onBeforeSetupMiddleware: function (devServer) {
      if (!devServer) {
        throw new Error('webpack-dev-server is not defined');
      }
      let func = require('./mock/index.js');
      return func(devServer);
    },
    open: true,
    host: "127.0.0.1",
    port: '8080',
  },

 

5. 新建mock/index.js
const Mock = require('mockjs')
const fs = require('fs')
const path = require('path')
function getJsonFile(filePath) {
  const json = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8')
  return JSON.parse(json)
}
module.exports = function (devServer) {
  if (process.env.Mock == 'TRUE') {
    devServer.app.get('/user/userinfo', (rep, res) => {
      let json = getJsonFile('./userinfo.json')
      res.json(Mock.mock(json))
    })
    devServer.app.post('/user/orderList', (rep, res) => {
      let json = getJsonFile('./orderList.json')
      res.json(Mock.mock(json))
    })
  }
}

6.新建mcck/userinfo.json

{
  "error": 0,
  "data": {
    "userid": "@id()",
    "username": "@cname()",
    "date": "@date()",
    "avatar": "@image('200x200','red','#fff','avatar')",
    "description": "@paragraph()",
    "ip": "@ip()",
    "email": "@email()"
  }
}

7.新建 .env.development

MOCK=TRUE

 

8.使用

  mounted() {
    axios.get("/user/userinfo").then(({ data }) => {
      console.log(data);
    });
  },

 

       

 

标签:vue,const,require,devServer,js,json,fs,mookjs,数据
来源: https://www.cnblogs.com/jqynr/p/16330549.html