Skip to content
Advertisement

Programmatically instantiate vuetify-components

I am trying to programmatically instantiate vuetify-components and add them to the DOM. With simple components like a v-card or v-dialoge it works fine, but it does not work with v-data-tables.

I created a codesandbox to showcase the problem: https://codesandbox.io/s/throbbing-butterfly-4ljhx?file=/src/components/MainWindow.vue

Look at the errors in the console when clicking the button to add a Table.

Can anyone help me out on how to add a table and why it throws these TypeErrors? Thanks!

Btw. I am following this guide: https://css-tricks.com/creating-vue-js-component-instances-programmatically/

Advertisement

Answer

You need to pass vuetify instance into extended Vue constructor same way as you do when instantiating main Vue instance…

MainWindow.vue

<template>
  <v-app>
    <v-btn @click="addTable" color="red">Generate Data-Table</v-btn>
    <hr>
    <v-btn @click="addCard">Generate simple Card</v-btn>
    <v-container ref="mainContainer"></v-container>
  </v-app>
</template>

<script>
import Table from "./Table.vue";
import Card from "./Card.vue";
import Vue from "vue";
import vuetify from "../plugins/vuetify";

export default {
  name: "mainWindow",
  components: { Table, Card },
  methods: {
    addTable() {
      var ComponentClass = Vue.extend(Table);
      var instance = new ComponentClass({ vuetify });
      instance.$mount();
      this.$refs.mainContainer.appendChild(instance.$el);
    },
    addCard() {
      var ComponentClass = Vue.extend(Card);
      var instance = new ComponentClass({});
      instance.$mount();
      this.$refs.mainContainer.appendChild(instance.$el);
    }
  }
};
</script>

<style>
</style>

Note: This is not recommended way of using dynamic components in Vue!

From the linked article:

In my case, I don’t know which component to insert in the template and also where to insert it. This information is only available at runtime

This is useful only when you do not know “where”. If you know “where”, “which” part is easily solvable with Dynamic Components

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement