老规矩----前面文章的步骤创建文件导入js等
1.carousel.vue 组件
<template>
<el-carousel ref="banner" class="lz-banner" :interval="5000" arrow="always" :autoplay="autoplay">
<el-carousel-item
v-for="(item, i) in imgList"
:key="i"
:name="'banner' + i"
>
<el-image :src="item.imgUrl" fit="scale-down" @click.stop="imgClick(item,i)" />
</el-carousel-item>
</el-carousel>
</template>
<script>
import { reactive, watch, ref, nextTick } from 'vue'
export default {
props: {
// 展示的数据列表
imgList: {
default() {
return []
},
type: Array
},
autoplay: {
default() {
return false
},
type: Boolean
},
activeNum: {
default() {
return 0
},
type: Number
}
},
emits: ['imgChange'],
setup(props, ctx) {
const banner = ref(null)
// 监听变化 改变图片的展示
watch(() => props.activeNum, (n) => {
// 要执行的方法
nextTick(() => {
banner.value.setActiveItem('banner' + n)
})
}, { immediate: true, deep: true })
const imgClick = (item, i) => {
ctx.emit('imgChange', item, i)
}
return { imgClick, banner }
}
}
</script>
<style lang="scss">
.lz-banner {
width: 400px;
height: 400px;
.el-carousel__container {
width: 400px;
height: 400px;
img {
display: block;
width: 100%;
height: 100%;
}
}
}
</style>
2.使用
<template>
<LZCarousel :img-list="carouselData.imgList" @imgChange="imgChange"></LZCarousel>
<div>
<el-image v-for="(item, i) in carouselData.imgList" :key="i" :src="item.imgUrl" style="width:100px;height:100px;" fit="scale-down" @click.stop="imgClick(item,i)" />
</div>
<LZDialog
:dialog-object="dialogObj"
@dialogClose="dialogClose"
@dialogSuccess="dialogSuccess"
>
<LZCarousel :active-num="carouselData.activeNum" :img-list="carouselData.imgList" @imgChange="imgChange2"></LZCarousel>
</LZDialog>
</template>
<script>
import { reactive, toRefs, ref, nextTick } from 'vue'
export default {
setup() {
const dialogObj = reactive({
dialogVisible: false,
title: '查看大图',
width: '40%',
successBtnText: '确定',
closeBtnText: '取消',
isFooter: true // 是否显示按钮
})
const carouselData = reactive({
activeNum: 0,
imgList: [
{
imgUrl:
''
},
{
imgUrl:
''
}
]
})
// 声明的变量 一定要和 refName传输的一样
const name1 = ref(null)
// 这个是方法的回调 点击谁展示谁
const imgChange = (item, i) => {
console.log(item)
console.log(i)
}
const imgChange2 = (item, i) => {
console.log(item)
console.log(i)
}
const imgClick = (item, i) => {
dialogObj.dialogVisible = true
carouselData.activeNum = i
}
const dialogClose = () => {
dialogObj.dialogVisible = false
}
const dialogSuccess = () => {
dialogObj.dialogVisible = false
}
return { carouselData, imgChange, imgChange2, name1, dialogObj, imgClick, dialogClose, dialogSuccess }
}
}
</script>