mockjs模拟数据请求

一般项目的方法

<html>

<head>

<script>

<script src="http://requirejs.org/docs/release/2.1.16/comments/require.js"></script>

</script>

</head>

</html>

<script>

// 配置 Mock 路径
require.config({
paths: {
mock: 'http://mockjs.com/dist/mock'
}
})

// 加载 Mock
require(['mock'], function(Mock) {

// Mock.mock(rurl, template)
Mock.mock('hello.json', {
'list|1-10': [{
'id|+1': 1,
'email': '@EMAIL',
'regexp3': /d{5,10}/
}]
})
$.ajax({
url: 'hello.json',
dataType: 'json'
}).done(function(data, status, jqXHR) {
$('<pre>').text(JSON.stringify(data, null, 4))
.appendTo('body')
})
})

</script>

vue-cli项目中

在src目录里面创建一个utils/mock.js

相关.vue文件引用

  import './utils/mock.js' 

   import axios from 'axios'

另main.js引入import axios from 'axios' 

注意这点,使用  Vue.prototype.$http = axios

mock.js编写示例如下,数据和暴露url

//src/utils/mock.js
//mock.js
import Mock from 'mockjs'

var url='/news',
export default(url,{
'list|1-10': [{
'id|+1': 1,
'email': '@EMAIL',
'regexp3': /d{5,10}/
}]
})

.vue组件里面请求

mounted() {
    //alert(1)
    this.$http.post('/news')
      .then(function(response) {
        console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      });
  }
原文地址:https://www.cnblogs.com/lwj820876312/p/9085560.html