Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject Vuetify into my custom vue plugin

I would like to create a Vue plugin with a function which programatically renders a Vue component. That component depends on Vuetify. Everything works fine if I use vanilla HTML/CSS in that component, but using Vuetify-related things in there (e.g. a ) does not work. I assume that I didn't inject vuetify itself into the component correctly.

In my custom component, I tried importing every Vuetify component separately, but without success. I also tried creating the component with the syntax: new Vue({vuetify}), but also without success.

import MyCustomComponent from '@/components/MyCustomComponent'
import vuetify from '@/plugins/vuetify';



export default {
  install(Vue, options) {
    function renderMyCustomComponent() {
        const CustomComponent= Vue.extend(MyCustomComponent)
        Vue.use(vuetify)
        let instance = new CustomComponent()
        instance.$mount()
        document.body.appendChild(instance.$el)
    }

    Vue.prototype.$renderMyComponent = renderMyCustomComponent
  }

}

The error message indicates, that vuetify (or at least some of it's properties) are not available in my component [Vue warn]: Error in getter for watcher "isDark": "TypeError: Cannot read property 'dark' of undefined"

HINT/EDIT: I am using Vuetify 2.0. The way Vuetify is injected into the app changed a little bit. Here's the code of my vuetify plugin file:

import Vue from 'vue';
import Vuetify from 'vuetify';
import 'vuetify/dist/vuetify.min.css';
import de from 'vuetify/es5/locale/de';

Vue.use(Vuetify)

export default new Vuetify({
  theme: {
    themes: {
      light: {
        primary: '#3f51b5',
        secondary: '#b0bec5',
        accent: '#8c9eff',
        error: '#b71c1c'
      },
    },
  },
});
like image 637
zunnzunn Avatar asked Jan 19 '26 13:01

zunnzunn


1 Answers

Not sure if you solved this issue, but I had the same problem where Vuetify in a plugin would not be initialized correctly.

Vuetify documentation states that you need to define a vuetify option when creating your vue instance:

new Vue({
  vuetify,
}).$mount('#app')

Fortunately, custom Vue plugins has an options parameter that we can use.

Here is the code that consumes your plugin:

const options = {}; // add other options here! (vuex, router etc.)
Vue.use(YourCustomPlugin, options);

new Vue(options).$mount('#app');

And here is your plugin code:

import vuetify from "./src/plugins/vuetify";

export default {
    install(Vue, options) { // options is undefined unless you pass the options param!
        Vue.component('my-custom-component', MyCustomComponent);
        Vue.use(Vuetify);
        options.vuetify = vuetify;
    }
};

The vuetify module is very simple:

import Vuetify from "vuetify";
import "vuetify/dist/vuetify.min.css";

const opts = {}

export default new Vuetify(opts);
like image 92
Rob Kozura Avatar answered Jan 21 '26 08:01

Rob Kozura