Render Material Design Lite (MDL) elements in Vue.js
Hello all,
Making Material Design Lite (MDL) work with Vue.js is fairly easy.
After adding MDL javascript, the CSS framework parse the DOM in order to enable events listeners required to provide certain behaviors (example: input validations). Since our Vue components are added after MDL has scanned the DOM, we should re-run a scan on each element we are adding asynchronously.
Declare once a Vue directive on your root component. We will use it to invoke the upgradeElement
function of MDL componentHandler
on component rendering:
// Material Design Lite directive
Vue.directive('mdl', {
bind(el) {
window.componentHandler.upgradeElement(el);
},
});
Now add the v-mdl
attribute to any MDL element you need to be upgraded:
<div v-mdl class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input v-model="age" class="mdl-textfield__input" type="text" pattern="-?[0-9]*(\.[0-9]+)?" min="0" max="200">
<label class="mdl-textfield__label">Age (years)</label>
<span class="mdl-textfield__error">Age is not a number!</span>
</div>
And the trick is done.
Please note that the v-mdl
directory is required only on elements that have Javascript interactions. Putting it on a grid element won’t have any effect. You should also know that the componentHandler
will upgrade all the child elements inside an element. If you only render a father element which possess the v-mdl
directive, you don’t need to put the same directory on the child elements contained inside it.
very helpful thank you!!
Just what I was looking for! Thank you very much!
Thank you so much!
Hi,
I am getting this error:
[Vue warn]: Error in directive mdl bind hook: “TypeError: Cannot read property ‘insertBefore’ of null”
found in
—> at src/slide-designer/slide-designer-action-bar.vue
at src/slide-designer/slide-designer.vue
at src/app.vue
Can you help.
Thanks