1.安装axios
npm install axios --save
2.在main.js中引入
import { createApp } from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
const app = createApp(App)
app.config.globalProperties.$http = axios;
app.use(VueAxios, axios)
3.在根目录下的public文件夹data文件夹下新建一个userlist.json文件内容如下
{
"data":{
"sucess":200,
"userList":[
{
"success":200,
"name":"王三",
"key":0,
"age":21,
"address":"海珠区琶洲会展中心"
},
{
"success":200,
"name":"李五",
"key":1,
"age":32,
"address":"海珠区花城大道北109号"
},
{
"success":200,
"name":"嘎子哥",
"key":2,
"age":37,
"address":"深圳市宝安区宝钢大道999号"
},
{
"success":200,
"name":"红豆",
"key":3,
"age":24,
"address":"阳江市小岗村101号"
},
{
"success":200,
"name":"大娟",
"key":4,
"age":30,
"address":"河源市白云大道"
},
{
"success":200,
"name":"嘎子哥",
"key":4,
"age":37,
"address":"深圳市宝安区宝钢大道999号"
},
{
"success":200,
"name":"红豆",
"key":6,
"age":24,
"address":"阳江市小岗村101号"
},
{
"success":200,
"name":"大娟",
"key":7,
"age":30,
"address":"河源市白云大道"
},
{
"success":200,
"name":"嘎子哥",
"key":8,
"age":37,
"address":"深圳市宝安区宝钢大道999号"
},
{
"success":200,
"name":"红豆",
"key":9,
"age":24,
"address":"阳江市小岗村101号"
},
{
"success":200,
"name":"大娟",
"key":10,
"age":30,
"address":"河源市白云大道"
}
]
}
}
4.在需要请求数据的文件里导入axios
import axios from 'axios'
5.请求
<script lang="ts" setup>
import axios from 'axios';
const dataSource: Ref<DataItem[]> = ref([]);
// 获取表格数据
const getTableList = () => {
axios.get('http://127.0.0.1:5173/data/userList.json').then((res) => {
console.log(res, 'res');
if (res.data.data.sucess == 200) {
dataSource.value = res.data.data.userList;
// data = res.data.data.userList;
} else {
alert('数据获取失败');
}
});
};
</script>
6.效果图