vue使用axios請求本地數據

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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容