fix(carousel): fix carousel don't update the indicator and items when data change(#1244)

* fix(carousel): add methods of remove item

* fix: if delete item is current item then go next

Co-authored-by: Ryan2128 <33176053+Ryan2128@users.noreply.github.com>
This commit is contained in:
BeADre 2021-01-24 18:19:04 +08:00 committed by GitHub
parent 80de9fc5e1
commit 59422d7fab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 7 deletions

View File

@ -43,6 +43,7 @@ export interface InjectCarouselScope {
type: string type: string
items: Ref<UnwrapRef<CarouselItem[]>> items: Ref<UnwrapRef<CarouselItem[]>>
loop: boolean loop: boolean
updateItems: (item: CarouselItem) => void addItem: (item: CarouselItem) => void
removeItem: (uid: number) => void
setActiveItem: (index: number) => void setActiveItem: (index: number) => void
} }

View File

@ -29,6 +29,7 @@ import {
computed, computed,
toRefs, toRefs,
getCurrentInstance, getCurrentInstance,
onUnmounted,
} from 'vue' } from 'vue'
import { import {
autoprefixer, autoprefixer,
@ -158,8 +159,8 @@ export default defineComponent({
// lifecycle // lifecycle
onMounted(() => { onMounted(() => {
if (injectCarouselScope.updateItems) { if (injectCarouselScope.addItem) {
injectCarouselScope.updateItems({ injectCarouselScope.addItem({
uid: instance.uid, uid: instance.uid,
...props, ...props,
...toRefs(data), ...toRefs(data),
@ -168,13 +169,17 @@ export default defineComponent({
} }
}) })
onUnmounted(() => {
if (injectCarouselScope.removeItem) {
injectCarouselScope.removeItem(instance.uid)
}
})
return { return {
data, data,
itemStyle, itemStyle,
translateItem, translateItem,
type: injectCarouselScope.type, type: injectCarouselScope.type,
handleItemClick, handleItemClick,
} }
}, },

View File

@ -236,10 +236,18 @@ export default defineComponent({
}) })
} }
function updateItems(item) { function addItem(item) {
items.value.push(item) items.value.push(item)
} }
function removeItem(uid) {
const index = items.value.findIndex(item => item.uid === uid)
if (index !== -1) {
items.value.splice(index, 1)
if(data.activeIndex === index) next()
}
}
function itemInStage(item, index) { function itemInStage(item, index) {
const length = items.value.length const length = items.value.length
if ( if (
@ -358,7 +366,8 @@ export default defineComponent({
type: props.type, type: props.type,
items, items,
loop: props.loop, loop: props.loop,
updateItems, addItem,
removeItem,
setActiveItem, setActiveItem,
}) })