天天看點

一行指令, 靜态json變身api

作為一個前端開發者, 你可以會遇到沒有測試資料的尴尬, 而這次我們用

json-server

, 優雅的解決這個問題

效果

關于 json-server

全局安裝方式:
npm install -g json-server
           
使用方式: 如果有一個名為

douyu.json

的檔案, 它的啟動指令為
json-server --watch douyu.json
           

啟動界面

json-server最外層json的值, 預設隻支援

數組

對象

使用axios送出請求

axios.get("http://localhost:3000/data")
.then(res=> {
    return (res.data.rl)
})
           

效果測試

動圖效果

核心代碼:

vue元件化代碼

<template>
    <div class="source-atom">
        <div v-for="anchorInfo in anchorsInfo" class="atom">
            <img  v-bind:src="anchorInfo['image']" height="200" width="200" alt="" v-bind:title="message">
            <section>
                <div class="title">{{ anchorInfo['name'] }}</div>
                <article>{{ anchorInfo['desc'] }}</article>
            </section>
        </div>
    </div>
</template>


<script>
import axios from 'axios';

export default {
    data: function() {
        return {
            message: "鬥魚主播",
            anchorsInfo: this.getPersonImageAddr()
        }
    },


    methods: {

        getPersonImageAddr: function(){
            let anchorsInfo = [];

            axios.get("http://localhost:3000/data")
            .then(res=> {
                return (res.data.rl)
            })
            .then(res=>{
                let anchorInfo = []
                for (let i = 0; i < res.length; i++){
                    let anchorInfo = {};
                    anchorInfo["name"] = res[i]['nn'];
                    anchorInfo["image"] = res[i]['rs1'];
                    anchorInfo["desc"] = res[i]['rn'];
                    anchorsInfo.push(anchorInfo)
                }
                return anchorsInfo;
            })
            return anchorsInfo
        }
    }
}

</script>

<style scoped lang="less">
    .source-atom {

        display: flex;
        flex-wrap: wrap;
        justify-content: center;
    }

    .atom{

        float: left;
        margin: 10px;
        padding: 10px;
        border: 1px solid #BDBDBD;

    }
    .title {

        font-size: 20px;
        color: #A84631
    }
    
</style>
           

資料來源:

https://www.douyu.com/gapi/rkc/directory/2_201/1
           

繼續閱讀