I am having a list of blog cards which I have converted to a carousel using Splide. Whenever I change to another page, I want to remove the existing Splide object. I want to use Svelte actions to achieve this but am unable to do it.
<script>
const splideAction = async (node, props)=>{
const module = await import("@splidejs/splide");
const Splide = module.default;
const splide_css = await import("@splidejs/splide/dist/css/splide.min.css");
const carousel = new Splide(".splide",{
perPage:3,
type:"loop",
rewind: true,
permove: 1,
autoplay: true,
breakpoints: {
750: {
perPage: 1
},
800:{
perPage: 2
}
}
}).mount();
return {
updated(){
carousel.update();
console.log("Updated")
},
destroy(){
carousel.destroy();
console.log("destroy")
}
}
}
</script>
<div class="splide" use:splideAction>
<div class="splide__track" >
<div class="splide__list" >
{#each [...metadata.related_articles] as article (article.id)}
<div class="splide__slide flex"><Card
title = "{article.title}"
date = "{article.date}"
slug = "{article.slug}"
category= "{article.category}"
image = "{article.image}"/></div>
{/each}
</div>
</div>
</div>
When I click the card to another blog posts, I generates a new Carousel and the Old one is still there, How do I remove it destroy
A few things:
<svelte:head>.carousel.update() would do. I don't think you need to return an "update" method from your action anyway, since your action isn't taking any parameters. The update method is meant to react to your action's parameters changing.mount, not the constructor. Because of this, destroy is being called on the wrong variable. Try something like this:const carousel = new Splide();
carousel.mount();
While your question is missing some context, the following component seems to work. I simplified the template since I don't have access to the article data. You can view it live in the Svelte REPL. I added a button to remove the component so you can see the carousel get destroyed.
<script>
import Splide from '@splidejs/splide';
function carousel(node) {
const splide = new Splide(node, {
perPage: 3,
type: "loop",
rewind: true,
permove: 1,
autoplay: true,
breakpoints: {
750: {
perPage: 1
},
800: {
perPage: 2
}
}
});
splide.mount();
return {
destroy: () => {
splide.destroy();
console.log('destroyed');
}
}
}
</script>
<svelte:head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@splidejs/splide@3.0.9/dist/css/splide.min.css">
</svelte:head>
<div class="splide" use:carousel>
<div class="splide__track">
<ul class="splide__list">
<li class="splide__slide">Slide 01</li>
<li class="splide__slide">Slide 02</li>
<li class="splide__slide">Slide 03</li>
</ul>
</div>
</div>
<style>
li {
height: 300px;
background: lightblue;
}
</style>