0

I'm using Carousel element of Materialize CSS in my Vue js project. When I route to the vue instance which has carousel element, it doesn't show the carousel element. When I refresh the page, it shows the carousel element. I tried with all vue instance lifecycle hooks but it's not working. What is the solution for this?

Note that I have included both Compiled and minified CSS and Javascript in index.html.

<template>
<div class="carousel">
    <a class="carousel-item" href="#one!">1</a>
    <a class="carousel-item" href="#two!">2</a>
    <a class="carousel-item" href="#three!">3</a>
    <a class="carousel-item" href="#four!">4</a>
    <a class="carousel-item" href="#five!">5</a>
</div>
</template>

<script>
export default {
    name: 'Home',
    created() {
        document.addEventListener('DOMContentLoaded', function() {
            var elems = document.querySelectorAll('.carousel');
            var instances = M.Carousel.init(elems, {
                fullWidth: true,
                indicators: true
            });
        });
    }
}
</script>

1 Answer 1

3

Don't use a DOMContentLoaded event. Vue already has lifecycle methods for this reason.

export default {
    name: 'Home',
    mounted() {
        var elems = document.querySelectorAll('.carousel');
        var instances = M.Carousel.init(elems, {
            fullWidth: true,
            indicators: true
        });
    }
};

You'll also need to define M if you're using just a script tag

// vue.config.js

module.exports = {
  chainWebpack: config => {
    config.externals({
      'M'
    })
  }
}

or download the script from npm and import M from 'materialize-css'.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.