问题
I am using Materialize css with Vue. I have installed as an npm module and imported it in main.js
import Material from "materialize-css";
import "materialize-css/dist/css/materialize.min.css";
import "materialize-css/dist/js/materialize.min.js";
Vue.use(Material);
All the css is working fine, however, whene I try to use any javascript component like materialbox like this
const mb = document.querySelectorAll(".materialboxed");
M.MaterialBox.init(mb, {});
It gives an error that "M" is not defined. What should I do? I have added materialize-css as a dependency to the package.json.
回答1:
Vue.use is for vue plugins. materialize-css is not a vue plugin. And you dont do stuff like document.querySelectorAll
in vue. And when you use something like M -> you need to import it first. Please read vue documentation and understand how it work first.
You should use something like vue-material or vuetify for vue, or otherwise if you will try to hack materialize-css to work with vue you end up in not really maintainable code
回答2:
I thought I would provide a different answer based my own experience. I like Materializecss and didn't want to use something else just because it is more tailored towards Vuejs. Materializecss seems to have a larger community and is also used by other people who use things like Reactjs, so I think it is somewhat rational to prefer it over a more niche library.
I use the following in main.js
:
import 'materialize-css/dist/css/materialize.css'
import 'materialize-css'
Also, in public/index.html
, I have the following for the icons:
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
For me this seems to work perfectly fine including when I use M.Toast...
etc. I think the difference is me using import 'materialize-css'
where you have import Material from "materialize-css"
.
As a side-note however, I do get ESLint errors when building which says 'M' is not defined
in spite of the code actually working. ESLint just does not know that it is there. To get rid of these, I used the following hacky approach of putting the lines below at the top of the modules where I use materialize:
// Get rid of those pesky eslint errors for Materialize-css
if (typeof M == "undefined") {var M = {}}
This has the nice effect of showing me where it is used in a similar vein as an import
statement at the top, but I'm sure there are good reasons why this is actually bad advice.
回答3:
Add following code in your component(say App.vue):
import M from 'materialize-css'
export default {
...
mounted () {
M.AutoInit()
},
...
来源:https://stackoverflow.com/questions/51429968/m-is-not-defined-when-using-materialize-css-with-vue