添加侧边栏实战课程

新建轮播组件

在 src/components 下新建 Slider.vue 文件,复制贴入以下代码:

src/components/Slider.vue

 1 <template>
 2   <div v-if="slides.length" class="carousel slide" @mouseover="stop" @mouseout="play">
 3     <div class="carousel-inner">
 4       <transition
 5         enter-active-class="animated slideInRight"
 6         leave-active-class="animated slideOutLeft"
 7       >
 8         <div v-if="show" key="current">
 9           <slot :currentSlide="currentSlide"></slot>
10         </div>
11         <div v-else key="next" class="item next">
12           <slot :currentSlide="currentSlide"></slot>
13         </div>
14       </transition>
15     </div>
16 
17     <div class="carousel-indicators">
18       <li v-for="n in slides.length" :class="{ active: n - 1 === currentIndex }" @click="playTo(n - 1)"></li>
19     </div>
20   </div>
21 </template>
22 
23 <script>
24 export default {
25   name: 'Slider',
26   props: {
27     // 轮播项
28     slides: {
29       type: Array,
30       default: () => []
31     },
32     // 是否自动轮播
33      autoplay: {
34       type: Boolean,
35       default: true
36     },
37     // 轮播延迟
38     delay: {
39       type: Number,
40       default: 3000
41     }
42   },
43   data() {
44     return {
45       currentIndex: 0, // 当前项索引
46       show: true // 是否显示当前项
47     }
48   },
49   computed: {
50     // 当前项
51     currentSlide() {
52       return this.slides[this.currentIndex]
53     },
54     // 下一项索引
55     nextIndex() {
56       if (this.currentIndex === this.slides.length - 1) {
57         return 0
58       } else {
59         return this.currentIndex + 1
60       }
61     }
62   },
63   mounted() {
64     if (this.autoplay) this.play()
65   },
66   methods: {
67     play() {
68       if (this.autoplay) {
69         this.interval = setInterval(() => {
70           this.playTo(this.nextIndex)
71         }, this.delay)
72       }
73     },
74     stop() {
75       if (this.interval) clearInterval(this.interval)
76     },
77     playTo(n) {
78       if (this.currentIndex === n) return
79       this.show = false
80       setTimeout(() => {
81         this.currentIndex = n
82         this.show = true
83       }, 0)
84     }
85   }
86 }
87 </script>
88 
89 <style scoped>
90 .carousel {margin-top:4px;padding-bottom:30px;}
91 .carousel-inner > div {min-height:177px;}
92 @media (min-width: 1200px){.carousel-inner > div {min-height:228px;}}
93 .carousel-indicators {bottom:0;border-radius: 12px;background-color: hsla(0,0%,100%,.3);margin-bottom: 0px;padding: 4px 8px;}
94 .carousel-indicators li {margin:0 3px;border:1px solid #ff8580;background-color: #f4665f;}
95 </style>

 

posted @ 2018-07-17 16:38  前端极客  阅读(244)  评论(0编辑  收藏  举报