【问题标题】:Programmatically instantiate vuetify-components以编程方式实例化 vuetify-components
【发布时间】:2020-12-29 19:31:06
【问题描述】:

我正在尝试以编程方式实例化 vuetify-components 并将它们添加到 DOM。使用 v-cardv-dialoge 之类的简单组件可以正常工作,但不适用于 v-data-tables

我创建了一个代码框来展示这个问题:https://codesandbox.io/s/throbbing-butterfly-4ljhx?file=/src/components/MainWindow.vue

单击按钮添加表格时查看控制台中的错误。

谁能帮助我了解如何添加表格以及为什么会抛出这些类型错误?谢谢!

顺便说一句。我正在关注本指南:https://css-tricks.com/creating-vue-js-component-instances-programmatically/

【问题讨论】:

    标签: javascript vue.js components vuetify.js


    【解决方案1】:

    您需要将 vuetify 实例传递给扩展的 Vue 构造函数,就像实例化主 Vue 实例时一样...

    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>
    

    注意:不推荐在 Vue 中使用动态组件的方式!

    来自链接的文章:

    就我而言,我不知道要在模板中插入哪个组件以及在哪里插入它。此信息仅在运行时可用

    这仅在您不知道“在哪里”时才有用。如果你知道“哪里”,“哪个”部分很容易用Dynamic Components解决

    【讨论】:

    • 如何将 props 传递给这个创建的组件?
    • const ComponentClass = Vue.extend({ props: ['name'], template: CustomTextField, });不工作,知道为什么吗?
    猜你喜欢
    • 2013-08-11
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    相关资源
    最近更新 更多