简体   繁体   中英

Materialize js doesn't work on first load

I am trying to make a Vue.js SPA chat app and I have problem with Materialize CSS and JS. JS doesn't work on first load and to make it work I have to reload the page. Not sure where the problem is since there are no errors in the console.

Here is index.html:

 <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css"> <title>Chat</title> </head> <body> <div id="app"></div> <!-- built files will be auto injected --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script> </body> </html> 

And here is the component where is the problem:

  <template> <div class="container reg"> <h1 class="text-centered">Registrace</h1> <form @submit.prevent="register"> * Another form fields * <div class="input-field col s12"> <select> <option value="" disabled selected>Choose your option</option> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> <label>Materialize Select</label> </div> <input type="submit" value="Registrovat" /> </form> <router-link :to="{ name: 'login' }"> <button>Login</button> </router-link> </div> </template> <script> document.addEventListener('DOMContentLoaded', function() { var elems = document.querySelectorAll('select'); var instances = M.FormSelect.init(elems, null); }); export default { data: function () { return { }; }, methods: { Register () { } } } </script> 

It seems use an external jQuery library is an anti-pattern with Vue.js, because

Vue.js and jquery fight over how the DOM is handled.

See the last comment here

I think you have to install it via npm and then insert manually the css and js in the compile process because I had the same problem with materialize and ionic 3.

If you wan't spend time finding a work-around way to import manually the css and js inside the compile process would be better to use a more Vue friendly solutions like this

I modified my answer to add another useful link. This library use the Materialize css and Vue.js to build UI appcomponents.org

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM