Alex Johnson
Alex Johnson

Reputation: 173

Proper MaterializeCSS initialization in VueJS Project

I try to init MaterializeCSS framework without jQuery in VueJS project, created with npm (vue init webpack projectname)

From version 1.0.0-rc.2 Materialize supports its own initialization without jQuery, smth like this:

  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.collapsible');
    var instances = M.Collapsible.init(elems, options);
  });

But with this way, JS Materialize Components work only after manual page reloading and when I open some component and return to component with Materialize stuff - it doesn't work - I need to reload page manually again all the time.

So how to init JS components in proper way?

Upvotes: 3

Views: 3535

Answers (1)

user10017742
user10017742

Reputation:

It worked for me so you may want to try this:

Go to your src/main.js file and add the following lines (if assume you are using npm):

import 'materialize-css/dist/js/materialize.min'

Personally, I use the M.AutoInit() way of initializing JS components on each vue component that needs them:

<template>
  <div class="componentName">
    <!-- Some HTML content -->
  </div>
</template>


<script>
  export default {
    name: 'componentName',

    data() {
      return {
        // Some values
      };
    },

    mounted() {
      M.AutoInit(); // That way, it is only initialized when the component is mounted
    }
  }
</script>


<style scoped>
  /* Some CSS */
</style>

Using M.AutoInit() or

document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.collapsible');
    var instances = M.Collapsible.init(elems, options);
  });

inside the mounted function of your component will result in them being called only when they are fully mounted.

Upvotes: 5

Related Questions