3

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?

1

1 Answer 1

5

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.

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

2 Comments

Why this method doesn't work when I try to use v-if and v-else construcntions? For example, I fetch data from server and I place my collpsible into v-else tag - to show some data in collpasible when it would be received
v-if and v-else remove the concerned node from the DOM so it is not mounted. The mounted method is called when the component is mounted into the DOM so try calling your initialization function in the created method instead

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.