• vue使用mock模拟数据操作


    首先下载mockjs

    npm install mockjs

    npm install axios

    之后在src文件夹下创建一个新的文件夹,名为mock

    在mock文件夹下创建一个index.js

    里面的内容为

    const Mock = require('mockjs');

    //设置ajax请求的相应的时间
    Mock.setup({
    timeout:'200-600'
    });

    let configArray = [];

    const files = require.context('.', true ,/.js$/);
    //使用webpack读取所有的mock文件
    files.keys().forEach((key)=> {
    if( key==='./index.js') return;
    configArray = configArray.concat(files(key).default);
    })

    //注册所有的mock服务
    configArray.forEach((item)=>{
    for (let [path, target] of Object.entries(item)) {
    let protocol = path.split('|')
    Mock.mock(new RegExp('^'+protocol[1]), protocol[0], target);
    }
    })

     

    之后在main.js进行引用

    import Vue from 'vue'
    import App from './App.vue'
    import router from './router'
    import store from './store'
    import axios from "axios";

    require('./mock');

    Vue.config.productionTip = false
    Vue.prototype.$axios = axios

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

     

    之后在mock文件夹下创建demoList.js文件,

    里面的内容为;


    // 获取 mock.Random 对象
    const Mock = require('mockjs')
    const Random = Mock.Random;

    let demoList = [{
    id: 1,
    name: 'zs',
    age: '23',
    job: Random.cname()
    },{
    id: 2,
    name: 'ww',
    age: '24',
    job: '后端工程师'
    }]

    export default {
    'get|/parameter/query': (option) => {
    return {
    status: 200,
    message: 'success',
    data: demoList
    };
    }
    }

     

    之后就可以在template组件中进行使用,运用axios库,就可以拿到自己定义的数据

    created() {
    this.$axios.get("/parameter/query").then((res)=>{
    console.log(res)
    })
    }

    问题统计

    1、如果你使用了eslint代码校验的话,会出项报错的情况

    报错信息:error 'option' is defined but never used no-unused-vars

    解决方法:在package.json中添加如下信息,即可解决。

    "rules": {
    "generator-star-spacing": "off",
    "no-tabs":"off",
    "no-unused-vars":"off",
    "no-console":"off",
    "no-irregular-whitespace":"off",
    "no-debugger": "off"
    }

  • 相关阅读:
    给部署在openshift上的WordPress添加wptouch插件
    让你的代码符合PEP8标准——sublime text 2 安装及使用 Python Flake8 Lint 插件
    Pylot——跨平台的网站压力测试工具
    window.print打印指定div
    window.parent与window.opener的区别 转
    获取Windows Mobile开发工具
    event.srcElement
    GridView的各种用法
    JS 中document详解
    llog
  • 原文地址:https://www.cnblogs.com/wenaq/p/15007638.html
Copyright © 2020-2023  润新知