用Vue和Axios实现一个刷猫App

功能介绍

直接打开html, 会显示一只猫咪照片. 点击照片, 会更新一张新的猫咪照片.

实现方法

  • 用Axios发送请求
  • 用Vue绑定img标签src属性

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Axios Demo1</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue@3.5.8/dist/vue.global.prod.js"></script>
</head>
<body>
    <div style="margin:0 auto; text-align: center;" id="app">
        <img @click="refresh" v-if="imgSrc" :src="imgSrc">{{imgSrc?'':'加载中'}}</img>
    </div>
    <script>
        const { createApp, ref, onMounted } = Vue
        const App = {
            setup(){
                // var imgSrc = ref('https://www.baidu.com/img/flexible/logo/pc/result@2.png')
                const imgSrc = ref('')
                onMounted(() => {
                    axios.get('https://api.thecatapi.com/v1/images/search')
                    .then((res)=> {
                        // handle success
                        console.log(res);
                        imgSrc.value = res.data[0].url
                    })
                })
                const refresh = () => {
                    console.log('refresh')
                    axios.get('https://api.thecatapi.com/v1/images/search')
                    .then((res)=> {
                        // handle success
                        console.log(res);
                        imgSrc.value = res.data[0].url
                    })
                }
                return {
                    imgSrc,
                    refresh
                }
            }
        }
        createApp(App).mount('#app');
        // console.log(Vue)
    </script>
</body>
</html>

效果

图片加载稍慢, 请稍等. 如果打不开可以刷新一下网页.

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部