使用 props 数据实例化扩展的 Vue JS 组件

Instanciating extended VueJS components with props data within

大家好,

让我给你一些关于我的问题的背景信息:

我正在尝试创建一个系统,只需按一下按钮即可在页面上添加图表。
这些图表将包含来自 MySQL 数据库的元素。

我有一个 Chart.vue 文件,其中包含单个 HighChart 元素的模板。它还包含一个道具:

export default {
    name : "Chart",
    props : ["tableToDisplay"],
    

然后我有一个名为“Test.vue”的主视图。
它从组件文件夹中导入 Chart.vue 然后我基本上只需要写 :

<Chart :table-to-display="tableToDisplay"/>

创建变量内包含的 table 图表的实例:this.tableToDisplay。

但这不是我想要做的:我想通过按一下按钮来创建图表,所以我做了一些更改:

<div>
    <button @click="createGraph">Add a graph</button>
    <Chart :table-to-display="tableToDisplay"/>
</div>

然后,我创建了方法:

        createGraph(event)
        {
            let ChartClass = Vue.extend(Chart)
            console.log(ChartClass)
            let graphInstance = new ChartClass({
                props:{
                    "tableToDisplay": this.tableToDisplay
                }
            })
            graphInstance.$mount()

            let divContainer = event.target.parentElement

            divContainer.append(graphInstance.$el)
        },

这就是我的问题所在。

在该方法中,我想发送一个 table 以显示到新创建的图表,但我似乎无法以这种方式操作道具值。

我认为这段代码就是解决方案:

           let graphInstance = new ChartClass({
                props:{
                    "tableToDisplay": this.tableToDisplay
                }
            })

但事实并非如此

当我点击按钮时,确实出现了一个空图表,但是属性“tableToDisplay”是未定义的。

我查看了控制台并收到“[Vue 警告]:已安装挂钩中的错误:“TypeError:密文为空”。 我是否在 ChartClass 中添加参数并不重要,我总是在 graphInstance.$mount() 行上出现此错误。

首先,我认为您不需要以编程方式实例化图表组件。一个简单的 v-for 循环就可以解决问题:

<template>
  <Chart v-for="table of chartTables :table-to-display="table"/>
</template>

<script>
...
data() {
   chartTables: []
},
methods: {
   createChart() {
      // Adding a new table to the array will create a new Chart component.
      this.chartTables.push(this.tableToDisplay)
   }
}
</script>

如果此解决方案适合您的需求,请继续!


也就是说,如果你真的需要自己实例化一个Vue组件,你必须使用propsData参数来传递你的props。

    const instance = new ChartClass({
      parent: this, // The parent is your current component
      propsData: {
        tableToDisplay: this.tableToDisplay,
      },
    })
    let divContainer = event.target.parentElement 
    instance.$mount(divContainer)

parent 选项非常重要:它将您的组件添加到 Vue 组件依赖树中。没有它,你的组件将没有继承属性(例如 Vuex 商店、插件等)。