[前端] VUE基础 (2) (轮播图、ajax)

一、vue实现简单轮播图

1.vue实现点击轮播图片

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Carousel</title>
</head>
<body>
<div id="app">
    <img :src="images[currentIndex].imgSrc" alt="cars">
    <br>
    <button @click = 'prevHandler'>上一张</button>
    <button @click = 'nextHandler'>下一张</button>
</div>
<script src="static/vue.js"></script>
<script>
    // 使用vue
    var app = new Vue({
        el: '#app',
        data() {
            return {
                // 图片数据
                images:[
                    {id:1,imgSrc:'./images/1.jpg'},
                    {id:2,imgSrc:'./images/2.jpg'},
                    {id:3,imgSrc:'./images/3.jpg'},
                    {id:4,imgSrc:'./images/4.jpg'},
                    {id:5,imgSrc:'./images/5.jpg'},
                ],
                // 当前显示图片的index,修改该值切换图片
                currentIndex:0
            }
        },
        methods: {
            // 下一张 点击事件
            nextHandler(){
                this.currentIndex++;
                if(this.currentIndex == 5){
                    this.currentIndex = 0;
                }
            },
            // 上一张 点击事件
            prevHandler(){
                this.currentIndex--;
                if(this.currentIndex == -1){
                    this.currentIndex = 4;
                }
            }
        }
    })
</script>
</body>
</html>

实现效果:

2.实现自动轮播

// 使用vue
var app = new Vue({
    el: '#app',
    data() {
        return {
            // 图片数据
            images:[
                {id:1,imgSrc:'./images/1.jpg'},
                {id:2,imgSrc:'./images/2.jpg'},
                {id:3,imgSrc:'./images/3.jpg'},
                {id:4,imgSrc:'./images/4.jpg'},
                {id:5,imgSrc:'./images/5.jpg'},
            ],
            // 当前显示图片的index,修改该值切换图片
            currentIndex:0
        }
    },
    methods: {
        // 下一张 点击事件
        nextHandler(){
            this.currentIndex++;
            if(this.currentIndex == 5){
                this.currentIndex = 0;
            }
        },
        // 上一张 点击事件
        prevHandler(){
            this.currentIndex--;
            if(this.currentIndex == -1){
                this.currentIndex = 4;
            }
        }
    },
    created(){
        setInterval( ()=>{  // 注意,这里使用箭头函数,其中的this指向vue实例,如果使用function(){}则this指向Window
            this.currentIndex++;
            if(this.currentIndex == 5){
                this.currentIndex = 0;
            }
        },2000)
    }
})

在Vue实例中使用了created方法,这个方法会在vue实例创建完后立即被执行,所以,我们一般在这个方法中实现ajax请求数据,以及创建定时器等操作。

这里使用setInterval定时器,每两秒让currentIndex递增,从而实现自动轮播。

注意:在created方法中,如果setInterval()中的函数是function(){}这种匿名函数,则他内部的this指向Window。所以我们使用()=>{}箭头函数来改变this的指向,让其指向vue实例,这样才能正确的拿到currentIndex的值。

建议:能用箭头函数,就不用普通匿名函数。

关于this指向问题,参考:https://blog.csdn.net/qq_36356218/article/details/80908021

实现效果:

二、vue使用jquery的ajax请求数据

1.路飞学城的数据api

https://www.luffycity.com/api/v1/course_sub/category/list/?belong=1

{
    "error_no": 0,
    "data": [{
        "id": 15,
        "name": "Python开发",
        "belong": 1,
        "hide": false,
        "category": 1
    }, {
        "id": 16,
        "name": "Linux云计算",
        "belong": 1,
        "hide": false,
        "category": 1
    }, {
        "id": 17,
        "name": "Web前端",
        "belong": 1,
        "hide": false,
        "category": 1
    }, {
        "id": 18,
        "name": "Java",
        "belong": 1,
        "hide": false,
        "category": 1
    }, {
        "id": 19,
        "name": "Go语言&C语言",
        "belong": 1,
        "hide": false,
        "category": 1
    }]
}

可以看到data列表中一共有5个对象。我们主要关注id、name和category三个属性。

2.vue中使用jQuery的ajax来请求数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JQueryAjax</title>
    <style>
        li{
            display: inline-block;
            border: 1px mistyrose solid;
            background-color: seashell;
            margin-right: 20px;
            font-size: 14px;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 循环categoryList,展示所有的category.name -->
    <ul>
        <li  v-for = '(category,index) in categoryList' :key = 'category.id'>{{ category.name }}</li>
    </ul>
</div>
<script src="static/vue.js"></script>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>
    // 使用vue
    var app = new Vue({
        el: '#app',
        data() {
            return {
                categoryList:[]
            }
        },
        methods: {},
        created(){
            $.ajax({
                // 从api获取数据
                url:"https://www.luffycity.com/api/v1/course_sub/category/list/?belong=1",
                // 请求方式为get,获取category列表
                type:"get",
                success: (data) =>{
                    if(data.error_no===0){
                        var data = data.data;
                        // 造一个"全部"
                        let obj = {
                            id:0,
                            name:"全部",
                            belong: 1,
                            hide: false,
                            category:1
                        }
                        // 将从后端获取的数据,赋值给vue中的categoryList
                        this.categoryList = data;
                        // 将我们自己造的"全部",添加到数据的最前面,注意id为0(获取的后台数据id从1开始)
                        this.categoryList.unshift(obj);
                    }
                }
            })
        }
    })
</script>
</body>
</html>

三、点击更改样式(操作class)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JQueryAjax</title>
    <style>
        li{
            display: inline-block;
            border: 1px mistyrose solid;
            background-color: seashell;
            margin-right: 20px;
            font-size: 14px;
        }
        li.active{
            color:red;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 循环categoryList,展示所有的category.name -->
    <ul class="v-li">
        <li @click="handlerClick(index)" :class="{active:index==currentIndex}" v-for = '(category,index) in categoryList' :key = 'category.id' >
            {{ category.name }}
        </li>
    </ul>
</div>
<script src="static/vue.js"></script>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script>
    // 使用vue
    var app = new Vue({
        el: '#app',
        data() {
            return {
                categoryList:[],
                currentIndex:0
            }
        },
        methods: {
            handlerClick(idx){
                this.currentIndex = idx;
            }
        },
        created(){
            $.ajax({
                // 从api获取数据
                url:"https://www.luffycity.com/api/v1/course_sub/category/list/?belong=1",
                // 请求方式为get,获取category列表
                type:"get",
                success: (data) =>{
                    if(data.error_no===0){
                        var data = data.data;
                        // 造一个"全部"
                        let obj = {
                            id:0,
                            name:"全部",
                            belong: 1,
                            hide: false,
                            category:1
                        }
                        // 将从后端获取的数据,赋值给vue中的categoryList
                        this.categoryList = data;
                        // 将我们自己造的"全部",添加到数据的最前面,注意id为0(获取的后台数据id从1开始)
                        this.categoryList.unshift(obj);
                    }
                }
            })
        }
    })
</script>
</body>
</html>

当我们点击某个<li>的时候,让currentIndex改变为他的index。然后在:class中,active样式是否生效,取决于index==currentIndex。所以,我们点击的<li>就会应用active样式。

实现效果:

四、vue实现MP3播放器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MusicPlayer</title>
    <style>
        #song_name{
            font-size: 14px;
            font-weight: bold;
        }
        #song_author {
            font-size: 10px;
            color: darkslategrey;
        }
        li{
            list-style: none;
        }
        li.active{
            color: dodgerblue;
        }
    </style>
</head>
<body>
<div id="app" style=" 300px">
    <!--  使用audio播放器标签  -->
    <audio :src="musicData[currentIndex].songSrc" controls autoplay @ended="endHandler"></audio>
    <!-- 循环musicList,展示所有的musics.name -->
    <ul>
        <!-- 循环歌曲列表数据,显示歌名和歌手名 -->
        <li @click="handlerClick(index)" :class="{active:index==currentIndex}" v-for = '(item,index) in musicData' :key = 'item.id' >
            <p id="song_name">{{ item.name }}</p>
            <p id="song_author">{{ item.author }}</p>
            <hr style="height:1px;border:none;border-top:1px solid #555555;" />
        </li>
    </ul>
</div>
<script src="static/vue.js"></script>
<script>
    // 造假数据
    var musicData = [
        {id:1,name:'Halo',author:'Beyoncé',songSrc:'musics/Beyoncé - Halo.mp3'},
        {id:2,name:'出埃及记',author:'Maksim Mrvica',songSrc:'musics/Maksim Mrvica - 出埃及记.mp3'},
        {id:3,name:'ナツのテーマ (纳兹专属音乐)',author:'高梨康治',songSrc:'musics/高梨康治 (たかなし やすはる) - ナツのテーマ (纳兹专属音乐).mp3'},
        {id:4,name:'魔法対戦',author:'高梨康治',songSrc:'musics/高梨康治 (たかなし やすはる) - 魔法対戦.mp3'},
        {id:5,name:'魔法発動',author:'高梨康治',songSrc:'musics/高梨康治 (たかなし やすはる) - 魔法発動.mp3'},
        {id:6,name:'鳳凰・滅びの力 (凤凰・毁灭之力)',author:'高梨康治',songSrc:'musics/高梨康治 (たかなし やすはる) - 鳳凰・滅びの力 (凤凰・毁灭之力).mp3'},
        {id:7,name:'只要为你活一天',author:'黄英华',songSrc:'musics/黄英华 - 只要为你活一天.mp3'},
    ]
    // 使用vue
    var app = new Vue({
        el: '#app',
        data() {
            return {
                musicData:[],
                currentIndex:0
            }
        },
        methods: {
            handlerClick(idx){
                // 点击歌曲列表中某歌时,切换
                this.currentIndex = idx;
            },
            endHandler(){
                // 当歌曲播放完毕后,自动切换到下一曲
                this.currentIndex++;
                if(this.currentIndex == 7){
                    this.currentIndex = 0;
                }
            }
        },
        created(){
            // 这里直接使用假数据,应该去后台获取数据的
            this.musicData = musicData;
        }
    })
</script>
</body>
</html>

解释:

1)<audio>标签的src由vue中的musicData[currentIndex].songSrc来驱动

2)<audio>标签中的@ended="endHandler"用来绑定事件函数(歌曲结束触发事件)

3)<li>标签中,循环musicData,展示歌曲列表,当被点击时,index==currentIndex,添加active样式(更改字体颜色),并且触发播放当前歌曲的事件函数 handlerClick(index)。

4)vue实例中created函数中,理论上应该使用ajax调用API接口获取实时歌曲列表数据,为了方便,使用假数据代替。

(✿◠‿◠)

原文地址:https://www.cnblogs.com/leokale-zz/p/12255952.html