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