--- tags: Mike課程 --- # Axios 非同步處理 ### ==取得get的值== * 利用get的方式 請求api 會回傳以下的訊息  * 就可以利用 res.data取得 api中的資料 ```javascript= const app = { setup() { axios .get('https://vue-lessons-api.herokuapp.com/photo/list') .then((res) => { console.log(res); //取得api data的值 console.log(res.data); }); return {}; }, }; Vue.createApp(app).mount("#app"); ``` ### ==使用時機== * 通常我們都會等到DOM元素加載完成後再去get api,這時我們就可以使用 生命週期的onMounted => DOM 渲染完成後執行。 ```javascript= <script> // 掛載 onMounted 生命週期函式 const { onMounted } = Vue; const app = { setup() { onMounted(() => { axios .get('https://vue-lessons-api.herokuapp.com/photo/list') .then((res) => { console.log(res); //取得api data的值 console.log(res.data); }); }) return {}; }, }; Vue.createApp(app).mount("#app"); </script> ``` ### ==渲染到畫面== * 將api的資料抓下來後,我們先運用reactive定義我們要放入的初始的資料 ```javascript= //定義初始資料 const imageArr = reactive({ arr: [] }); ``` * 抓到res 傳來的資料塞入imageArr.arr 預先準備好的空陣列 ```javascript= onMounted(() => { axios .get('https://vue-lessons-api.herokuapp.com/photo/list') .then((res) => { //抓到res 傳來的資料塞入imageArr.arr 預先準備好的空陣列 imageArr.arr = res.data; }); }) ``` * 利用v-for迴圈 印出 imageArr.arr資料 ```htmlembedded= <div> <!-- 利用v-for迴圈 印出 imageArr.arr資料--> <img class="img" v-for="item in imageArr.arr" :key="item.url" :src="item.url" alt="" /> </div> ``` ### ==邏輯處理== * 我們以處理點選 下一張與上一張圖片做例子 1. 利用ref定義一個開關,初始化為0 ```javascript= // 定義換頁初始值 const imageInd = ref(0); ``` 2. 上下頁的按鈕 ```javascript= // 下一頁 const addGet = () => { imageInd.value++ //處理索引值變0的判定 if (imageInd.value < 0) { imageInd.value = imageArr.arr.length - 1 } } // 上一頁 const addRemove = () => { imageInd.value-- //處理索引值變0的判定 if (imageInd.value > imageArr.arr.length - 1) { imageInd.value = 0 } ``` 3. 用v-show判斷如果初始值 === 索引值 就顯示 ```htmlembedded= v-show="imageInd === i" ``` 4. 再加入button中 點擊含式 ```htmlembedded= <a href="javascript:;" @click="addRemove">上一張</a> <a href="javascript:;" @click="addGet">下一張</a> ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up