商城我的项目应用nuxt架构
应用轮播图,抉择了时下最热门的vue-awesome-swiper作为根底组件。然而应用过程中遇到的坑,真的很好受
nuxt的版本是2.14.6
在vuecli中构建应用vue-awesome-swiper组件没有任何问题,
然而加上ssr就始终会报错,原生组件的切换上一个下一个的按钮不显示,即使是显示了点击也不会失效,前面排查也不晓得是不是电脑硬件的问题,咱们应用要求切换按钮须要自定义(包含按钮行为)
这儿间接上咱们目前的组件代码
<template> <div v-swiper:mySwiper="sweiperConfig.options" :style="{ width: `${sweiperConfig.width}px`, height: `${sweiperConfig.height}px` }"> <div class="swiper-wrapper"> <slot name="swiperbody"></slot> </div> <a-icon v-if="iconConfig.prevShow" class="swiper-left-btn" :style="{ ...iconConfig.iconCss }" type="left" :disabled="iconConfig.prevDisabled" @click="prev" /> <a-icon v-if="iconConfig.nextShow" class="swiper-right-btn" :style="{ ...iconConfig.iconCss }" type="right" :disabled="iconConfig.nextDisabled" @click="next" /> </div></template><script>export default { props: { // sweiper配置,options是sweiper官网配置,具体请查看官网文档 sweiperConfig: { type: Object, default: () => { return { options: { type: Object, default: () => {} }, width: { type: Number, default: 300 }, height: { type: Number, default: 300 } } } }, // icon配置,这是配置自定义的图标的款式 iconConfig: { type: Object, default: () => { return { prevShow: { type: Boolean, default: true }, nextShow: { type: Boolean, default: true }, prevDisabled: { type: Boolean, default: false }, nextDisabled: { type: Boolean, default: false }, iconCss: { type: Object, default: () => { return { 'font-size': '30px', padding: '10px', top: '50%' } } } } } } }, mounted() { // 回传mySwiper实例,不便父组件应用该实例进行操作(调用办法或者事件) // 在父组件中对应的$emit办法定义到method中就能间接获取该实例,具体应用参考下文代码块中 this.$emit('getSwiperObj', this.mySwiper) }, methods: { prev() { this.mySwiper.slidePrev() //内置办法,往上翻一页 // 以后的页码 this.$emit('prevClick', this.mySwiper.realIndex + 1) }, next() { this.mySwiper.slideNext() //内置办法,往下翻一页 // 以后的页码 this.$emit('nextClick', this.mySwiper.realIndex + 1) } }}</script><style lang="scss" scoped>@mixin swiper-btn { background-color: #fff; border-radius: 50%; position: absolute; z-index: 2;}.swiper-wrapper { .swiper-slide { &:hover { cursor: pointer; } } .img-wrapper img { margin: auto; width: 200px; height: 100px; background-image: linear-gradient(gray 100%, transparent 0); }}.swiper-left-btn { @include swiper-btn; left: 5px;}.swiper-right-btn { @include swiper-btn; right: 5px;}.swiper-left-btn,.swiper-right-btn { &:hover { background-color: #ccc; }}</style>
须要特地留神的是,<slot name="swiperbody"></slot>
,这里的slot,在页面内应用要用v-slot的形式,这儿v-slot简写,不分明的去vue官网查看
class="sweiper-slide"
这个属性不能丢掉,这是sweiper源码获取子元素用的
<VueSwiper :sweiper-config="sweiperConfig" :icon-config="iconConfig" @getSwiperObj="getSwiperObj" @prevClick="prevClick" @nextClick="nextClick"> <template #swiperbody> <img v-for="(img, index) in imgs" :key="index" :src="img.url" class="swiper-slide" /> </template></VueSwiper>
参考文章: nuxt应用vue-awesome-sweiper采坑