vue关于mock的简单使用_蓝瞳_前端开发者

一、mock

1、简介

  mock是一个模拟数据生成器,旨在帮助前端独立于后端进行开发,帮助编写单元测试。其可模拟 Ajax 并返回模拟数据,使前端不用去调用后端的接口,方便测试。
 

2、vue直接使用mock

step1:安装mock

npm install mockjs
npm install mockjs

 

step2:直接引入mock.js,并编写mock接口(Mock.mock)。

【mock.js】
//引入mock模块
import Mock from 'mockjs';

Mock.mock('/login', { //输出数据
    'name': '@name', //随机生成姓名
    //还可以自定义其他数据
});
Mock.mock('/list', { //输出数据
    'name': '@name', //随机生成姓名
    'age|10-20': 10
    //还可以自定义其他数据
});
【mock.js】
//引入mock模块
import Mock from 'mockjs';

Mock.mock('/login', { //输出数据
    'name': '@name', //随机生成姓名
    //还可以自定义其他数据
});
Mock.mock('/list', { //输出数据
    'name': '@name', //随机生成姓名
    'age|10-20': 10
    //还可以自定义其他数据
});

【mock.js】
//引入mock模块
import Mock from ‘mockjs’;

Mock.mock(‘/login’, { //输出数据
‘name’: ‘@name’, //随机生成姓名
//还可以自定义其他数据
});
Mock.mock(‘/list’, { //输出数据
‘name’: ‘@name’, //随机生成姓名
‘age|10-20’: 10
//还可以自定义其他数据
});

 

step3:在需要的地方引入编写后的接口js即可。

【App.vue<template>
    <div>
        <button @click="login">login</button>
        <button @click="list">list</button>
    </div>
    <!--App -->
</template>

<script>
    import mock from './mock.js'
    import axios from 'axios'
    export default {
        methods: {
            login() {
                axios.post("/login").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.name)
                    }
                })
            },
            
            list() {
                axios.post("/list").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.name + ',' + response.data.age)
                    }
                })
            }
        }
    }
</script>

<style>

</style>
【App.vue<template>
    <div>
        <button @click="login">login</button>
        <button @click="list">list</button>
    </div>
    <!--App -->
</template>

<script>
    import mock from './mock.js'
    import axios from 'axios'
    export default {
        methods: {
            login() {
                axios.post("/login").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.name)
                    }
                })
            },
            
            list() {
                axios.post("/list").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.name + ',' + response.data.age)
                    }
                })
            }
        }
    }
</script>

<style>

</style>

【App.vue
<template><div><button @click=”login”></button><button @click=”list”></button></div><!–App –></template><script>
import mock from
./mock.js
import axios from
axios
export
default {
methods: {
login() {
axios.post(
/login).then(response => {
if (response.data) {
console.log(response.data)
alert(response.data.name)
}
})
},

list() {
axios.post(/list).then(response => {
if (response.data) {
console.log(response.data)
alert(response.data.name
+,+ response.data.age)
}
})
}
}
}
</script><style></style>

 

step4:代码与截图
  目录结构。使用vue-cli创建项目(详见https://www.cnblogs.com/l-y-h/p/11241503.html)。

 

 

完整代码

【main.js】
import vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')


【mock.js】
//引入mock模块
import Mock from 'mockjs';

Mock.mock('/login', { //输出数据
    'name': '@name', //随机生成姓名
    //还可以自定义其他数据
});
Mock.mock('/list', { //输出数据
    'name': '@name', //随机生成姓名
    'age|10-20': 10
    //还可以自定义其他数据
});



【App.vue】
<template>
    <div>
        <button @click="login">login</button>
        <button @click="list">list</button>
    </div>
    <!--App -->
</template>

<script>
    import mock from './mock.js'
    import axios from 'axios'
    export default {
        methods: {
            login() {
                axios.post("/login").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.name)
                    }
                })
            },
            
            list() {
                axios.post("/list").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.name + ',' + response.data.age)
                    }
                })
            }
        }
    }
</script>

<style>

</style>
【main.js】
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')


【mock.js】
//引入mock模块
import Mock from 'mockjs';

Mock.mock('/login', { //输出数据
    'name': '@name', //随机生成姓名
    //还可以自定义其他数据
});
Mock.mock('/list', { //输出数据
    'name': '@name', //随机生成姓名
    'age|10-20': 10
    //还可以自定义其他数据
});



【App.vue】
<template>
    <div>
        <button @click="login">login</button>
        <button @click="list">list</button>
    </div>
    <!--App -->
</template>

<script>
    import mock from './mock.js'
    import axios from 'axios'
    export default {
        methods: {
            login() {
                axios.post("/login").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.name)
                    }
                })
            },
            
            list() {
                axios.post("/list").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.name + ',' + response.data.age)
                    }
                })
            }
        }
    }
</script>

<style>

</style>

【main.js】
import Vue from ‘vue’
import App from ‘./App.vue’

Vue.config.productionTip = false

new Vue({
render: h => h(App),
}).$mount(‘#app’)

【mock.js】
//引入mock模块
import Mock from ‘mockjs’;

Mock.mock(‘/login’, { //输出数据
‘name’: ‘@name’, //随机生成姓名
//还可以自定义其他数据
});
Mock.mock(‘/list’, { //输出数据
‘name’: ‘@name’, //随机生成姓名
‘age|10-20’: 10
//还可以自定义其他数据
});

【App.vue】
<template><div><button @click=”login”></button><button @click=”list”></button></div><!–App –></template><script>
import mock from
./mock.js
import axios from
axios
export
default {
methods: {
login() {
axios.post(
/login).then(response => {
if (response.data) {
console.log(response.data)
alert(response.data.name)
}
})
},

list() {
axios.post(/list).then(response => {
if (response.data) {
console.log(response.data)
alert(response.data.name
+,+ response.data.age)
}
})
}
}
}
</script><style></style>

 

运行截图:
初始画面

 

 

点击login 按钮(随机产生一个人名)

 

 

点击list按钮(随机产生一个人名和年龄)

 

 

3、Vue项目中使用webpack-api-mocker进行mock

step1:安装webpack-api-mocker

npm i webpack-api-mocker --save-dev
npm i webpack-api-mocker --save-dev

 

step2:编写 /mocker/index.js,用于定义mock接口

【/mocker/index.js】
// 使用 require 引入json文件,可以直接访问数据
const appData = require('../data.json')

const proxy = {
    'GET /api/login': {
        success: appData.login.success,
        message: appData.login.message
    },
    'GET /api/list': [{
            id: 1,
            username: 'kenny',
            sex: 6
        },
        {
            id: 2,
            username: 'kenny',
            sex: 6
        }
    ],
    'POST /api/post': (req, res) => {
        res.send({
            status: 'error',
            code: 403
        });
    },
    'DELETE /api/remove': (req, res) => {
        res.send({
            status: 'ok',
            message: '删除成功!'
        });
    }
}
module.exports = proxy
【/mocker/index.js】
// 使用 require 引入json文件,可以直接访问数据
const appData = require('../data.json')

const proxy = {
    'GET /api/login': {
        success: appData.login.success,
        message: appData.login.message
    },
    'GET /api/list': [{
            id: 1,
            username: 'kenny',
            sex: 6
        },
        {
            id: 2,
            username: 'kenny',
            sex: 6
        }
    ],
    'POST /api/post': (req, res) => {
        res.send({
            status: 'error',
            code: 403
        });
    },
    'DELETE /api/remove': (req, res) => {
        res.send({
            status: 'ok',
            message: '删除成功!'
        });
    }
}
module.exports = proxy

【/mocker/index.js】
// 使用 require 引入json文件,可以直接访问数据
const appData = require(‘../data.json’)

const proxy = {
‘GET /api/login’: {
success: appData.login.success,
message: appData.login.message
},
‘GET /api/list’: [{
id: 1,
username: ‘kenny’,
sex: 6
},
{
id: 2,
username: ‘kenny’,
sex: 6
}
],
‘POST /api/post’: (req, res) => {
res.send({
status: ‘error’,
code: 403
});
},
‘DELETE /api/remove’: (req, res) => {
res.send({
status: ‘ok’,
message: ‘删除成功!’
});
}
}
module.exports = proxy

 

step3:修改 vue.config.js 配置文件(若不存在,在项目下新建即可)

【vue.config.js】
const path = require('path')
const apiMocker = require('webpack-api-mocker')

module.exports = {
  devServer: {
    before(app) {
    // 注意,此处引用的是自定义的接口文件 apiMocker(app, path.resolve('./mocker/index.js'), { proxy: { '/repos/*': 'https://api.github.com/', }, changeHost: true, }) } } }
【vue.config.js】
const path = require('path')
const apiMocker = require('webpack-api-mocker')

module.exports = {
  devServer: {
    before(app) {
    // 注意,此处引用的是自定义的接口文件 apiMocker(app, path.resolve('./mocker/index.js'), { proxy: { '/repos/*': 'https://api.github.com/', }, changeHost: true, }) } } }

【vue.config.js】
const path = require(‘path’)
const apiMocker = require(‘webpack-api-mocker’)

module.exports = {
devServer: {
before(app) {
    // 注意,此处引用的是自定义的接口文件
apiMocker(app, path.resolve(‘./mocker/index.js’), {
proxy: {
‘/repos/*’: ‘https://api.github.com/’,
},
changeHost: true,
})
}
}
}

 

step4:随便定义一组 json 数据(用于测试)。

{
    "login": {
      "success": "true",
      "message": "登陆成功"
    },
    "fileList": {
      "success":"true",
      "list":[
      {"fileId":"1","fileName":"a1.c","content":"content-test1"
      },
      {"fileId":"2","fileName":"a2.c","content":"content-test2"
      },
      {"fileId":"3","fileName":"a3.c","content":"content-test2"
      },
      {"fileId":"4","fileName":"a4.c","content":"content-test2"
      },
      {"fileId":"5","fileName":"a5.c","content":"content-test2"
      },
      {"fileId":"6","fileName":"a8.c","content":"content-test2"
      },
      {"fileId":"7","fileName":"a9.c","content":"content-test2"
      }]
    }
}
{
    "login": {
      "success": "true",
      "message": "登陆成功"
    },
    "fileList": {
      "success":"true",
      "list":[
      {"fileId":"1","fileName":"a1.c","content":"content-test1"
      },
      {"fileId":"2","fileName":"a2.c","content":"content-test2"
      },
      {"fileId":"3","fileName":"a3.c","content":"content-test2"
      },
      {"fileId":"4","fileName":"a4.c","content":"content-test2"
      },
      {"fileId":"5","fileName":"a5.c","content":"content-test2"
      },
      {"fileId":"6","fileName":"a8.c","content":"content-test2"
      },
      {"fileId":"7","fileName":"a9.c","content":"content-test2"
      }]
    }
}

{
“login”: {
“success”: “true”,
“message”: “登陆成功”
},
“fileList”: {
“success”:”true”,
“list”:[
{“fileId”:”1″,”fileName”:”a1.c”,”content”:”content-test1″
},
{“fileId”:”2″,”fileName”:”a2.c”,”content”:”content-test2″
},
{“fileId”:”3″,”fileName”:”a3.c”,”content”:”content-test2″
},
{“fileId”:”4″,”fileName”:”a4.c”,”content”:”content-test2″
},
{“fileId”:”5″,”fileName”:”a5.c”,”content”:”content-test2″
},
{“fileId”:”6″,”fileName”:”a8.c”,”content”:”content-test2″
},
{“fileId”:”7″,”fileName”:”a9.c”,”content”:”content-test2″
}]
}
}

 

step5:完整代码、截图
文件目录结构:

 

 

完整代码

【main.js】
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')


【App.vue】
<template>
    <div>
        <button @click="login">login</button>
        <button @click="list">list</button>
        <button @click="post">post</button>
        <button @click="remove">remove</button>
    </div>
    <!--App -->
</template>

<script>
    import axios from 'axios'
    export default {
        methods: {
            login() {
                axios.get("/api/login").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.success + ',' + response.data.message)
                    }
                })
            },
            
            list() {
                axios.get("/api/list").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        let list1 = response.data[0].id + ',' + response.data[0].sex + ',' + response.data[0].username
                        let list2 = response.data[1].id + ',' + response.data[1].sex + ',' + response.data[1].username
                        alert(list1 + '\n' + list2)
                    }
                })
            },
            
            post() {
                axios.post("/api/post").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.status + ',' + response.data.code)
                    }
                })
            },
            
            remove() {
                axios.delete("/api/remove").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.status + ',' + response.data.message)
                    }
                })
            }
        }
    }
</script>

<style>

</style>



【data.json】
{
    "login": {
      "success": "true",
      "message": "登录成功"
    },
    "fileList": {
      "success":"true",
      "list":[
      {"fileId":"1","fileName":"a1.c","content":"content-test1"
      },
      {"fileId":"2","fileName":"a2.c","content":"content-test2"
      },
      {"fileId":"3","fileName":"a3.c","content":"content-test2"
      },
      {"fileId":"4","fileName":"a4.c","content":"content-test2"
      },
      {"fileId":"5","fileName":"a5.c","content":"content-test2"
      },
      {"fileId":"6","fileName":"a8.c","content":"content-test2"
      },
      {"fileId":"7","fileName":"a9.c","content":"content-test2"
      }]
    }
}
  
  
  
【vue.config.js】
const path = require('path')
const apiMocker = require('webpack-api-mocker')

module.exports = {
  devServer: {
    before(app) {
        // path.resolve 引入mock
      apiMocker(app, path.resolve('./mocker/index.js'), {
        proxy: {
          '/repos/*': 'https://api.github.com/',
        },
        changeHost: true
      })
    }
  }
}



【/mocker/index.js】
// 使用 require 引入json文件,可以直接访问数据
const appData = require('../data.json')

const proxy = {
    'GET /api/login': {
        success: appData.login.success,
        message: appData.login.message
    },
    'GET /api/list': [{
            id: 1,
            username: 'kenny',
            sex: 6
        },
        {
            id: 2,
            username: 'kenny',
            sex: 6
        }
    ],
    'POST /api/post': (req, res) => {
        res.send({
            status: 'error',
            code: 403
        });
    },
    'DELETE /api/remove': (req, res) => {
        res.send({
            status: 'ok',
            message: '删除成功!'
        });
    }
}
module.exports = proxy
【main.js】
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')


【App.vue】
<template>
    <div>
        <button @click="login">login</button>
        <button @click="list">list</button>
        <button @click="post">post</button>
        <button @click="remove">remove</button>
    </div>
    <!--App -->
</template>

<script>
    import axios from 'axios'
    export default {
        methods: {
            login() {
                axios.get("/api/login").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.success + ',' + response.data.message)
                    }
                })
            },
            
            list() {
                axios.get("/api/list").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        let list1 = response.data[0].id + ',' + response.data[0].sex + ',' + response.data[0].username
                        let list2 = response.data[1].id + ',' + response.data[1].sex + ',' + response.data[1].username
                        alert(list1 + '\n' + list2)
                    }
                })
            },
            
            post() {
                axios.post("/api/post").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.status + ',' + response.data.code)
                    }
                })
            },
            
            remove() {
                axios.delete("/api/remove").then(response => {
                    if (response.data) {
                        console.log(response.data)
                        alert(response.data.status + ',' + response.data.message)
                    }
                })
            }
        }
    }
</script>

<style>

</style>



【data.json】
{
    "login": {
      "success": "true",
      "message": "登录成功"
    },
    "fileList": {
      "success":"true",
      "list":[
      {"fileId":"1","fileName":"a1.c","content":"content-test1"
      },
      {"fileId":"2","fileName":"a2.c","content":"content-test2"
      },
      {"fileId":"3","fileName":"a3.c","content":"content-test2"
      },
      {"fileId":"4","fileName":"a4.c","content":"content-test2"
      },
      {"fileId":"5","fileName":"a5.c","content":"content-test2"
      },
      {"fileId":"6","fileName":"a8.c","content":"content-test2"
      },
      {"fileId":"7","fileName":"a9.c","content":"content-test2"
      }]
    }
}
  
  
  
【vue.config.js】
const path = require('path')
const apiMocker = require('webpack-api-mocker')

module.exports = {
  devServer: {
    before(app) {
        // path.resolve 引入mock
      apiMocker(app, path.resolve('./mocker/index.js'), {
        proxy: {
          '/repos/*': 'https://api.github.com/',
        },
        changeHost: true
      })
    }
  }
}



【/mocker/index.js】
// 使用 require 引入json文件,可以直接访问数据
const appData = require('../data.json')

const proxy = {
    'GET /api/login': {
        success: appData.login.success,
        message: appData.login.message
    },
    'GET /api/list': [{
            id: 1,
            username: 'kenny',
            sex: 6
        },
        {
            id: 2,
            username: 'kenny',
            sex: 6
        }
    ],
    'POST /api/post': (req, res) => {
        res.send({
            status: 'error',
            code: 403
        });
    },
    'DELETE /api/remove': (req, res) => {
        res.send({
            status: 'ok',
            message: '删除成功!'
        });
    }
}
module.exports = proxy

【main.js】
import Vue from ‘vue’
import App from ‘./App.vue’

Vue.config.productionTip = false

new Vue({
render: h => h(App),
}).$mount(‘#app’)

【App.vue】
<template><div><button @click=”login”></button><button @click=”list”></button><button @click=”post”></button><button @click=”remove”></button></div><!–App –></template><script>
import axios from
axios
export
default {
methods: {
login() {
axios.get(
/api/login).then(response => {
if (response.data) {
console.log(response.data)
alert(response.data.success
+,+ response.data.message)
}
})
},

list() {
axios.get(/api/list).then(response => {
if (response.data) {
console.log(response.data)
let list1
= response.data[0].id +,+ response.data[0].sex +,+ response.data[0].username
let list2
= response.data[1].id +,+ response.data[1].sex +,+ response.data[1].username
alert(list1
+\n+ list2)
}
})
},

post() {
axios.post(/api/post).then(response => {
if (response.data) {
console.log(response.data)
alert(response.data.status
+,+ response.data.code)
}
})
},

remove() {
axios.delete(/api/remove).then(response => {
if (response.data) {
console.log(response.data)
alert(response.data.status
+,+ response.data.message)
}
})
}
}
}
</script><style></style>

【data.json】
{
“login”: {
“success”: “true”,
“message”: “登录成功”
},
“fileList”: {
“success”:”true”,
“list”:[
{“fileId”:”1″,”fileName”:”a1.c”,”content”:”content-test1″
},
{“fileId”:”2″,”fileName”:”a2.c”,”content”:”content-test2″
},
{“fileId”:”3″,”fileName”:”a3.c”,”content”:”content-test2″
},
{“fileId”:”4″,”fileName”:”a4.c”,”content”:”content-test2″
},
{“fileId”:”5″,”fileName”:”a5.c”,”content”:”content-test2″
},
{“fileId”:”6″,”fileName”:”a8.c”,”content”:”content-test2″
},
{“fileId”:”7″,”fileName”:”a9.c”,”content”:”content-test2″
}]
}
}

【vue.config.js】
const path = require(‘path’)
const apiMocker = require(‘webpack-api-mocker’)

module.exports = {
devServer: {
before(app) {
// path.resolve 引入mock
apiMocker(app, path.resolve(‘./mocker/index.js’), {
proxy: {
‘/repos/*’: ‘https://api.github.com/’,
},
changeHost: true
})
}
}
}

【/mocker/index.js】
// 使用 require 引入json文件,可以直接访问数据
const appData = require(‘../data.json’)

const proxy = {
‘GET /api/login’: {
success: appData.login.success,
message: appData.login.message
},
‘GET /api/list’: [{
id: 1,
username: ‘kenny’,
sex: 6
},
{
id: 2,
username: ‘kenny’,
sex: 6
}
],
‘POST /api/post’: (req, res) => {
res.send({
status: ‘error’,
code: 403
});
},
‘DELETE /api/remove’: (req, res) => {
res.send({
status: ‘ok’,
message: ‘删除成功!’
});
}
}
module.exports = proxy

 

运行截图:
点击 login 按钮

 

 

点击 list 按钮

 

 

点击 post 按钮

 

 

点击remove按钮

 

» 本文来自:前端开发者 » 《vue关于mock的简单使用_蓝瞳_前端开发者》
» 本文链接地址:https://www.rokub.com/73696.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!