3.
axios 存取資料
- 中文手冊:https://juejin.cn/post/6844903919907258382#articleHeader19
- 安裝
npm install --save axios vue-axios
- 一般會等動元素都渲染完成才去執行api,以免資料抓回來沒地方塞,也就是
onMounted(()=>{})
中去執行api
<div id="app">
<ul class="box" v-show="isLoad">
<li v-for="(news, i) in allNews.data" :key="news.nsn">
{{i + 1}}. <a :href="news.url">{{news.news_title}}</a>
</li>
</ul>
<img v-show="!isLoad" class="load" src="https://i.giphy.com/media/52qtwCtj9OLTi/giphy.webp" alt="" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.20.0/axios.min.js"></script>
<script src="https://unpkg.com/vue@next"></script>
<script>
const { ref, reactive, onMounted } = Vue;
const app = {
setup() {
const allNews = reactive({ data: [] });
const isLoad = ref(false);
onMounted(() => {
axios.defaults.baseURL = "https://www.lces.tn.edu.tw";
axios
.get("/modules/tadnews/app_api.php?op=list_all_news")
.then((res) => {
allNews.data = res.data;
isLoad.value = true;
})
.catch((error) => {
console.dir(error);
});
});
return {
allNews,
isLoad,
};
},
};
Vue.createApp(app).mount("#app");
</script>
-
完整範例: