javascript - Vue JS - 使用 innerHTML 呈现的动态创建的组件不能绑定(bind)到事件

标签 javascript vue.js vue-good-table

我最近才开始深入研究 Vue JS - 到目前为止我很喜欢它。 我现在面临一个问题,我正在尝试创建一个(重要的)表(使用 vue-good-table 插件),其中每个单元格都是它自己的一个组件。

阅读插件文档后,有人提到可以创建一个 HTML 列类型,您可以在其中使用原始 HTML(我猜): https://xaksis.github.io/vue-good-table/guide/configuration/column-options.html#html

为了简化事情,我有一个 Vue 组件(称为 Dashboard2.vue),它包含表格和名为 Test.vue 的子组件

我正在为每个相关单元格动态创建测试组件,并将其分配给相关行单元格。 因为我已经将列定义为 HTML 类型,所以我使用 innerHTML 属性从 Vue 组件中提取原始 HTML。 (关注本文https://css-tricks.com/creating-vue-js-component-instances-programmatically/) 一切进展顺利,仪表板看起来正是我想要的样子,但是当单击每个测试组件内的按钮时,没有任何反应。

我怀疑,由于我使用了 innerHTML 属性,它只是以某种方式跳过了 Vue even 处理程序机制,所以我有点卡住了。

这里是相关的组件部分:

Dashboard2.vue:

<template>
  <div>
    <vue-good-table
      :columns="columns"
      :rows="rows"
      :search-options="{enabled: true}"
      styleClass="vgt-table condensed bordered"
      max-height="700px"
      :fixed-header="true"
      theme="black-rhino">
    </vue-good-table>
  </div>
</template>

<script>
import axios from 'axios';
import Vue from 'vue';
import { serverURL } from './Config.vue';
import Test from './Test.vue';

export default {
  name: 'Dashboard2',
  data() {
    return {
      jobName: 'team_regression_suite_for_mgmt',
      lastXBuilds: 7,
      builds: [],
      columns: [
        {
          label: 'Test Name',
          field: 'testName',
        },
      ],
      rows: [],
    };
  },
  methods: {
    fetchResults() {
      const path = `${serverURL}/builds?name=${this.jobName}&last_x_builds=${this.lastXBuilds}`;
      axios.get(path)
        .then((res) => {
          this.builds = res.data;
          this.builds.forEach(this.createColumnByBuildName);
          this.createTestsColumn();
          this.fillTable();
        })
        .catch((error) => {
          // eslint-disable-next-line no-console
          console.error(error);
        });
    },
    createBaseRow(build) {
      return {
        id: build.id,
        name: build.name,
        cluster: build.resource_name,
        startTime: build.timestamp,
        runtime: build.duration_min,
        estimatedRuntime: build.estimated_duration_min,
        result: build.result,
      };
    },
    addChildRows(build, children) {
      const row = this.createBaseRow(build);
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < build.sub_builds.length; i++) {
        const currentBuild = build.sub_builds[i];
        if (currentBuild.name === '') {
          this.addChildRows(currentBuild, children);
        } else {
          children.push(this.addChildRows(currentBuild, children));
        }
      }
      return row;
    },
    createColumnByBuildName(build) {
      this.columns.push({ label: build.name, field: build.id, html: true });
    },
    addRow(build) {
      const row = this.createBaseRow(build);
      row.children = [];
      this.addChildRows(build, row.children);
      this.rows.push(row);
    },
    createTestsColumn() {
      const build = this.builds[0];
      const row = this.createBaseRow(build);
      row.children = [];
      this.addChildRows(build, row.children);
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < row.children.length; i++) {
        this.rows.push({ testName: row.children[i].name });
      }
    },
    fillBuildColumn(build) {
      const row = this.createBaseRow(build);
      row.children = [];
      this.addChildRows(build, row.children);
      // eslint-disable-next-line no-plusplus
      for (let i = 0; i < row.children.length; i++) {
        const childBuild = row.children[i];
        const TestSlot = Vue.extend(Test);
        const instance = new TestSlot({
          propsData: {
            testName: childBuild.name,
            result: childBuild.result,
            runTime: childBuild.runtime.toString(),
            startTime: childBuild.startTime,
            estimatedRunTime: childBuild.estimatedRuntime.toString(),
          },
        });
        instance.$mount();
        this.rows[i] = Object.assign(this.rows[i], { [build.id]: instance.$el.innerHTML });
      }
    },
    fillTable() {
      this.builds.forEach(this.fillBuildColumn);
    },
  },
  created() {
    this.fetchResults();
  },
};
</script>

<style scoped>

</style>

测试.vue

<template>
    <div>
  <b-card :header="result" class="mb-2" :bg-variant="variant"
          text-variant="white">
    <b-card-text>Started: {{ startTime }}<br>
      Runtime: {{ runTime }} min<br>
      Estimated: {{ estimatedRunTime }} min
    </b-card-text>
    <b-button @click="sayHi" variant="primary">Hi</b-button>
  </b-card>
</div>
</template>

<script>
export default {
  name: 'Test',
  props: {
    id: String,
    testName: String,
    build: String,
    cluster: String,
    startTime: String,
    runTime: String,
    estimatedRunTime: String,
    result: String,
  },
  computed: {
    variant() {
      if (this.result === 'SUCCESS') { return 'success'; }
      if (this.result === 'FAILURE') { return 'danger'; }
      if (this.result === 'ABORTED') { return 'warning'; }
      if (this.result === 'RUNNING') { return 'info'; }
      return 'info';
    },
  },
  methods: {
    sayHi() {
      alert('hi');
    },
  },
};
</script>

<style scoped>

</style>

我知道这是很多代码。 具体相关部分(在Dashboard2.vue中)是fillBuildColumn

再一次 - 我是 Vue JS 的新手 - 据说我的直觉告诉我我是 在这里做错了很多事。

任何帮助将不胜感激。

编辑:

通过丢失 innerHTML 属性和 html 类型,我得到了一个:

"RangeError: Maximum call stack size exceeded" thrown by the browser. Not sure what's causing it

最佳答案

我做了一个CodeSandbox样本。我可能弄乱了数据部分。但它给出了这个想法。

fillBuildColumn(build) {
  const row = this.createBaseRow(build);
  row.children = [];
  this.addChildRows(build, row.children);
  // eslint-disable-next-line no-plusplus
  for (let i = 0; i < row.children.length; i++) {
    const childBuild = row.children[i];
// i might have messed up with the data here
    const propsData = {
      testName: childBuild.name,
      result: childBuild.result,
      runTime: childBuild.runtime.toString(),
      startTime: childBuild.startTime,
      estimatedRunTime: childBuild.estimatedRuntime.toString()
    };

    this.rows[i] = Object.assign(this.rows[i], {
      ...propsData
    });
  }
}

createColumnByBuildName(build) {
  this.columns.push({
    label: build.name,
    field: "build" + build.id //guessable column name
  });
}
<vue-good-table :columns="columns" :rows="rows">
  <template slot="table-row" slot-scope="props">
          <span v-if="props.column.field.startsWith('build')">
            <Cell
              :testName="props.row.testName"
              :build="props.row.build"
              :cluster="props.row.cluster"
              :startTime="props.row.startTime"
              :runTime="props.row.runTime"
              :estimatedRunTime="props.row.estimatedRunTime"
              :result="props.row.result"
            ></Cell>
          </span>
          <span v-else>{{props.formattedRow[props.column.field]}}</span>
        </template>
</vue-good-table>

这个想法是在模板中渲染一个组件并有条件地进行。给出可猜测的列名的原因是使用像 <span v-if="props.column.field.startsWith('build')"> 这样的条件.由于您只有 1 个静态字段,其余字段是动态的,您也可以使用 props.column.field !== 'testName' .我在渲染时遇到问题,我必须在全局注册表格插件和 Cell 组件。

关于javascript - Vue JS - 使用 innerHTML 呈现的动态创建的组件不能绑定(bind)到事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59134548/

相关文章:

jquery - Bootstrap 形式 : How to dynamically create unique names for radio buttons

Vue.js - 使用 Vuelidate url 域应与电子邮件域匹配

javascript - VueJS : Google Maps loads before data is ready - how to make it wait?(Nuxt)

laravel - 如何在我的 View 端组件中显示 vue-good-table 中的自定义内容?

javascript - 如何使用 jQuery 添加新的 HTML 节点

javascript - 重新排序 HTML 元素并更改内容

javascript - 为什么我的 sequelize 模型实例丢失了它的 id?

javascript - HighChart 饼图工具提示已修复