Skip to content

Commit

Permalink
Merge pull request #929 from negezor/refactor-vue
Browse files Browse the repository at this point in the history
refactor(vue): optimize reactivity handling and reduce bundle size
  • Loading branch information
davidjerleke authored Jul 12, 2024
2 parents 387a3fa + 4b3d40c commit 910a8dc
Showing 1 changed file with 28 additions and 16 deletions.
44 changes: 28 additions & 16 deletions packages/embla-carousel-vue/src/components/emblaCarouselVue.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import { Ref, ref, isRef, watch, onMounted, onBeforeUnmount } from 'vue'
import {
Ref,
MaybeRef,
isRef,
watch,
onMounted,
onBeforeUnmount,
shallowRef
} from 'vue'
import {
areOptionsEqual,
arePluginsEqual,
Expand All @@ -16,45 +24,49 @@ export type EmblaCarouselVueType = [
]

function emblaCarouselVue(
options: EmblaOptionsType | Ref<EmblaOptionsType> = {},
plugins: EmblaPluginType[] | Ref<EmblaPluginType[]> = []
options: MaybeRef<EmblaOptionsType> = {},
plugins: MaybeRef<EmblaPluginType[]> = []
): EmblaCarouselVueType {
const storedOptions = ref(isRef(options) ? options.value : options)
const storedPlugins = ref(isRef(plugins) ? plugins.value : plugins)
const emblaNode = ref<HTMLElement>()
const emblaApi = ref<EmblaCarouselType>()
const isRefOptions = isRef(options)
const isRefPlugins = isRef(plugins)

let storedOptions = isRefOptions ? options.value : options
let storedPlugins = isRefPlugins ? plugins.value : plugins

const emblaNode = shallowRef<HTMLElement>()
const emblaApi = shallowRef<EmblaCarouselType>()

function reInit() {
if (!emblaApi.value) return
emblaApi.value.reInit(storedOptions.value, storedPlugins.value)
emblaApi.value.reInit(storedOptions, storedPlugins)
}

onMounted(() => {
if (!canUseDOM() || !emblaNode.value) return
EmblaCarousel.globalOptions = emblaCarouselVue.globalOptions
emblaApi.value = EmblaCarousel(
emblaNode.value,
storedOptions.value,
storedPlugins.value
storedOptions,
storedPlugins
)
})

onBeforeUnmount(() => {
if (emblaApi.value) emblaApi.value.destroy()
})

if (isRef(options)) {
if (isRefOptions) {
watch(options, (newOptions) => {
if (areOptionsEqual(storedOptions.value, newOptions)) return
storedOptions.value = newOptions
if (areOptionsEqual(storedOptions, newOptions)) return
storedOptions = newOptions
reInit()
})
}

if (isRef(plugins)) {
if (isRefPlugins) {
watch(plugins, (newPlugins) => {
if (arePluginsEqual(storedPlugins.value, newPlugins)) return
storedPlugins.value = newPlugins
if (arePluginsEqual(storedPlugins, newPlugins)) return
storedPlugins = newPlugins
reInit()
})
}
Expand Down

0 comments on commit 910a8dc

Please sign in to comment.