mockjs 사용 입문

37837 단어 자바 scriptvue.js
본 고 는 다른 사내 블 로 그 를 참고 하여 정리 한 것 으로 코드 가 미리 복사 되 어 원문 링크 를 기록 하지 못 해 원문 링크 를 제시 할 수 없다.
mockjs 를 왜 써 요?
전후 단 분리 프로젝트 가 개발 되 었 을 때 백 엔 드 인터페이스 가 완성 되 지 않 았 을 때 전단 에서 수 동 아 날로 그 인 터 페 이 스 를 개발 하여 데이터 요청 페이지 렌 더 링 을 완성 하고 백 엔 드 인터페이스 가 완성 되면 연결 효율 을 높 일 수 있 습 니 다.
mockjs 설치
npm install mockjs npm install axios -- save (설치 되 었 습 니까? 무시 하 십시오)
디 렉 터 리 구조
개인 용법, 참고, 표준 / src / mock / index. js / src / mock / user. js
user.js
import Mock from "mockjs"; //   mockjs
const Random = Mock.Random; // Mock.Random       ,          

//        
export const user_list = (params)=>{
    let list = []; 
    doCustomTimes(10,()=>{
        list.push(Mock.mock({           

            //basic
            'boolean': Random.boolean(), //           。
            'natural': Random.natural(1,100), //           (     0    )
            'integer': Random.integer(1, 100), //   1 100     
            'float': Random.float(0, 100, 0, 5), //   0 100      ,       0 5 
            'character': Random.character(), //       ,        
            'string': Random.string( '          ', 3, 5 ),//         。
            'range': Random.range(0, 10, 2), //         

            //date
            'date': Random.date('yyyy-MM-dd'), //         ,          
            'time': Random.time('HH:mm:ss'), //        
            'datetime': Random.datetime(), //                。
            'now': Random.now(), //              。

            //image
            'image': Random.image('200x100', '#00405d', '#FFF', 'Mock.js') ,//           。
            'dataImage':Random.dataImage( Random.size, 'hello' ),//        Base64     。

            //color
            'color': Random.color(),//             ,    '#RRGGBB'。
            'hex': Random.hex(), //             ,    '#RRGGBB'。
            'rgb':Random.rgb(), //             ,    'rgb(r, g, b)'。
            'rgba': Random.rgba(), //             ,    'rgba(r, g, b, a)'。
            'hsl': Random.hsl(), //             ,    'hsl(h, s, l)'。

            //text
            'paragraph': Random.paragraph( 3, 7 ), //         。
            'cparagraph': Random.cparagraph( 1, 3 ), //           。
            'sentence': Random.sentence( 1, 3 ), //         ,           。
            'csentence': Random.csentence( 1, 3 ),//           。
            'word': Random.word( 1, 3 ),//         。
            'cword': Random.cword('           ', 10,15),//    10 15 
            'title': Random.title( 3, 5 ), //         ,            。
            'ctitle': Random.ctitle( 3, 7 ), //           。

            //name
            'first': Random.first(),//             。
            'last': Random.last(),//             。
            'name': Random.name(),//              。
            'cfirst': Random.cfirst(),//             。
            'clast': Random.clast(), //             。
            'cname': Random.cname(),//             。

            //web
            'url': Random.url('http','baidu.com'), //        URL。
            'protocol': Random.protocol(), //       URL   
            'domain': Random.domain(), //        。
            'tld': Random.tld(), //          
            'email':Random.email('qq.com'),//        
            'ip':Random.ip(),//       IP   。

            //address
            'region':Random.region(),//      (  )  。
            'province':Random.province(),//      (  ) (    、   、     )
            'city':Random.city(true),//   。          。
            'county':Random.county(true),//      (  ) 。
            'zip':Random.zip(),//          (    )
            'address': Random.province(), //     

            //helper
            'capitalize': Random.capitalize('hello'),//               。
            'upper': Random.upper( 'hello' ),//         。
            'lower': Random.lower( 'HELLO' ),//         。
            'pick': Random.pick( ['a', 'e', 'i', 'o', 'u'] ),//            ,   。
            'shuffle': Random.shuffle( ['a', 'e', 'i', 'o', 'u'] ), //          ,   。

            //miscellaneous
            'guid': Random.guid(), //       GUID。
            'id': Random.id(), //       18     。
            'increment': Random.increment(2), //           。   2
        }));

    });
    return list;
}

export const user_info = (param)=>{
    let list = [];
    doCustomTimes(4,()=>{
        list.push(Mock.mock({
            "name":Random.cname(),
            "id":Random.id(),
            "mobileNumber":randomPhoneNum()
        }));
    });

    return list
}
/**
 * @param {Number} times            
 * @param {Function} callback     
 */
export const doCustomTimes = (times, callback) => {
    let i = -1
    while (++i < times) {
        callback(i)
    }
}
//       
export const randomPhoneNum = ()=>{
    var numArray = new Array("139","138","137","136","135","134","159","158","157","150","151","152","188","187","182","183","184","178","130","131","132","156","155","186","185","176","133","153","189","180","181","177");
    console.log()
    var lastArray = Math.random().toString().substring(2,10)
    var phoneNumber = numArray[Math.floor(Math.random()*(numArray.length))].toString() + lastArray
    return phoneNumber
}

index.js
import Mock from 'mockjs'

import { user_list , user_info } from "./user";


//   Ajax    ,                  
Mock.setup({
    timeout: 1000
})

//  
Mock.mock('/user/list', user_list)

Mock.mock('/user/info', user_info)


export default Mock

사용 하 는 vue 파일 에서 직접 요청 하면 됩 니 다.
created() {
    this.$axios.get('/user/info',{page:1,pagesize:10}).then(res=>{
    console.log(res)
})

유용 한 지식 을 만 나 저축 하 는 것 은 이미 불 시의 수요 에 대비 하 였 다.

좋은 웹페이지 즐겨찾기