<template>
<div>
<!-- 获取固定数据 -->
<h3>获取固定数据</h3>
<div>
直接定义:const list = [{ name: "湖北公司" }, { name: "宜昌公司" }];
<br />
<ul>
<li v-for="item in list">
{{ item.name }}
</li>
</ul>
</div>
<!-- 获取json数据,使用ref -->
<h3>使用axios以ref方式获取本地json数据</h3>
<div>
静态资源存放在public下,下面创建json/company.json文件,内容如下:<br />
{ "company":[ { "id":"600", "name":"湖北公司" }, { "id":"601",
"name":"宜昌公司" } ] }
<ul>
<li v-for="item in listRef">{{ item.id }} ---{{ item.name }}</li>
</ul>
</div>
<!-- 获取json数据,使用reactive -->
<div>
<h3>使用axios以reactive方式获取本地json数据</h3>
<ul>
<li v-for="item in data.list">{{ item.id }}---{{ item.name }}</li>
</ul>
</div>
<!-- 获取api数据,使用axios-->
<div>
<h3>使用axios获取api数据WeatherForecast</h3>
<ul>
<li v-for="item in data.weather">
{{ item.date }}---{{ item.temperatureC }}---{{ item.summary }}
</li>
</ul>
</div>
<button type="button" @click="weather">点击获取天气预报</button>
</div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import axios from "axios";
// 获取固定数据
const list = [{ name: "湖北公司" }, { name: "宜昌公司" }];
// 获取json数据,使用ref
const listRef = ref();
onMounted(async () => {
const res = await axios.get("./json/company.json");
listRef.value = res.data.company;
});
// 获取json数据,使用reactive
const data = reactive({
list: [],
weather: [],
});
const getCompanyInfo = async () => {
const res = await axios.get("./json/company.json");
data.list = res.data.company;
};
getCompanyInfo();
// 获取天气预报
const apiURL = "http://127.0.0.1:8888/WeatherForecast";
const getWeather = async () => {
await axios.get(apiURL).then((res) => {
data.weather = res.data;
});
};
getWeather();
// 点击天气预报
const weather = () => {
axios.get(apiURL).then((res) => {
console.log(res.data);
});
};
// 生命周期函数,加载完成执行
onMounted(() => {
console.log("生命周期函数");
});
</script>