mockjs在vue的使用

src/mock/mock.js

const Mock = require('mockjs');

// 获取 mock.Random 对象

const Random = Mock.Random;

// mock一组数据

const produceNewsData = function() {

    let articles = [];

    for (let i = 0; i < 100; i++) {

        let newArticleObject = {

            title: Random.csentence(5, 30), // Random.csentence( min, max )

            thumbnail_pic_s: Random.dataImage('300x250', 'mock的图片'), // Random.dataImage( size, text ) 生成一段随机的 Base64 图片编码

            author_name: Random.cname(), // Random.cname() 随机生成一个常见的中文姓名

            date: Random.date() + ' ' + Random.time(), // Random.date()指示生成的日期字符串的格式,默认为yyyy-MM-dd;Random.time() 返回一个随机的时间字符串

        };

        articles.push(newArticleObject);

    }



    return {

        articles,

    };

};



const login = () => ({

msg: 'success',

status: 1,

});



const CarouselPictures = () => {

    let picturesList = [];

    for (let i = 0; i < 4; i++) {

        picturesList.push(Random.image('853x160', Mock.mock('@color'), '#FFF', 'png', `Itis${i + 1}thpictures`));

    }

    return {

        picturesList,

    };

};



const goodsInfos = () => {

    let goodsInfo = [];

    for (let i = 0; i < 30; i++) {

        let goods = {};

        goods.image = Random.image('185x185', Mock.mock('@color'), '#FFF', 'png', `Itis${i + 1}thgoodss`);

        goods.price = Mock.mock({ 'number|100-200': 200 }).number;

        goods.title = Mock.mock('@title(3, 5)');

        goods.content = Mock.mock('@paragraph(1)');

        goodsInfo.push(goods);

    };

    return {

        goodsInfo,

    };

};



const searchGoodsByKey = (options) => {

    let num = Mock.mock({ 'number|10-20': 20 }).number;

    let searchList = [];

    for (let i = 0; i < num; i++) {

        let goods = {};

        goods.image = Random.image('185x185', Mock.mock('@color'), '#FFF', 'png', `Itis${i + 1}thgoodss`);

        goods.price = Mock.mock({ 'number|100-200': 200 }).number;

        goods.title = options.url.split('=')[1] + Mock.mock('@title(3, 5)');

        goods.content = options.url.split('=')[1] + Mock.mock('@paragraph(1)');

        searchList.push(goods);

    }

    return {

        searchList,

    };

};



// Mock.mock( url, post/get , 返回的数据);

Mock.mock('/news/getNews', 'post', produceNewsData);

Mock.mock('/user/login', 'post', login);

Mock.mock('/pictures/carouselPictures', CarouselPictures);

Mock.mock('/goods/goodsInfos', goodsInfos);

Mock.mock(/\/goods\/searchGoodsByKey\?key=(.*)/, 'get', searchGoodsByKey);

main.js

require('../src/mock/mock');

 

search.vue

methods: {

searchGoodsByKey(key){

this.$axios.get(`/goods/searchGoodsByKey?key=${key}`)

.then(data => {

this.searchlist = data.data.searchList;

})

.catch(error=>{

console.log(error);

});

},

},

 

你可能感兴趣的:(mockjs在vue的使用)