Home » vue » Materialize css triggers are not working in Vue js

Materialize css triggers are not working in Vue js

Posted by: admin November 26, 2021 Leave a comment

Questions:

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>
Answers:

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'.