美文网首页
vue使用axios请求本地数据

vue使用axios请求本地数据

作者: 梧桐芊雨 | 来源:发表于2019-05-13 20:42 被阅读0次
    1,安装

    在对应项目中安装axios:
    npm istall axios --save


    安装.png
    2,建立本地json数据。

    在static文件夹下建立mock文件夹,存放json数据


    json.png

    json格式如下

    {
      "success": true,
      "data":{
        "friend": [{
          "id": "001",
          "name": "萧古",
          "address": "徐州人士"
        }, {
          "id": "002",
          "name":"sweet甜",
          "address": "安徽人士"
        }, {
          "id": "003",
          "name":"大脸猫",
          "address": "徐州人士"
        }, {
          "id": "004",
          "name":"初见",
          "address": "淮安人士"
        }, {
          "id": "005",
          "name": "凉茶",
          "address": "南京人士"
        }, {
          "id": "006",
          "name":"看茶听学",
          "address": "安徽人士"
        }, {
          "id": "007",
          "name":"顽皮大朋友",
          "address": "安徽人士"
        }
      ]
      }
    }
    
    3.使用axios。

    在对应的组件中引用axios

    import axios from 'axios'
    

    通过mounted方法调用,并请求数据

     methods: {
        getFriend () {
          axios.get('../../static/mock/friend.json').then(this.getFriendInfo)
        },
        getFriendInfo (res) {
          console.log('axios数据请求结果', res)
          if (res.data.success) {
            this.friends = res.data.data.friend
          }
        }
      },
      mounted () {
        this.getFriend()
      }
    

    该组件代码显示

    <template>
      <div class="helloWord">
        <h3>朋友列表</h3>
        <mt-cell v-for="(item,index) in friends" :key="index" :title="item.name" :value="item.address"></mt-cell>
      </div>
    </template>
    
    <script>
    import axios from 'axios'
    export default {
      name: 'HelloWorld',
      data () {
        return {
          friends: []
        }
      },
      methods: {
        getFriend () {
          axios.get('../../static/mock/friend.json').then(this.getFriendInfo)
        },
        getFriendInfo (res) {
          console.log('axios数据请求结果', res)
          if (res.data.success) {
            this.friends = res.data.data.friend
          }
        }
      },
      mounted () {
        this.getFriend()
      }
    }
    </script>
    
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped>
    </style>
    
    4.请求结果

    console打印结果显示:


    结果.png

    页面效果显示


    结果.png

    相关文章

      网友评论

          本文标题:vue使用axios请求本地数据

          本文链接:https://www.haomeiwen.com/subject/jfxdaqtx.html