繁体   English   中英

如何从字符串中呈现vuejs组件

[英]How can I render a vuejs component from a string

我有一个vue组件创建一个4 td的表体,第一个td捕获id,后面分别是date,items和options按钮。 我能够显示数据但选项按钮显示为字符串而不是显示为html元素。

我尝试过使用v-html,但它可以解决我的问题

样本数据

{id: 4, date: "Jun 21, 2019", damage: 2}

零件

<table-body :data="purchases" :cells="formatCells()"></table-body>

格式化功能

formatCells(){
            return [
                { path: 'id', label: 'Id'},
                { path: 'date', label: 'Date'},
                { path: 'damage', label: 'Damage'},
                { key: 'option', content: purchase => '<table-row-options title="Options" :options="formatTableRowOptions(data)"/>'}
            ]
        }

表体组件

<template>
<tbody>
<tr v-for="item in data">
    <td v-for="cell in cells">{{renderCell(item, cell) }}</td>
</tr>
</tbody>

<script>
import _ from 'lodash'
export default {
    name: "table-body",
    props:['cells', 'data'],
    data(){
        return {
            options:''
        }
    },
    methods: {
        renderCell(item, cell) {
            if(cell.content) return cell.content(item)
            return _.get(item, cell.path)
        }
    }
}

我希望用户能够通过选项按钮查看表数据。 关于如何解决这个问题的任何建议?

最佳解决方案将取决于您需要如何通用。 你可以使用render功能全render但你可以通过调整插槽的内容来实现你想要的。

例如,您可以将table-row-options的呈现移动到模板中:

<template>
  <tbody>
    <tr v-for="item in data">
      <td v-for="cell in cells">
        <table-row-options
          v-if="cell.key === 'option'"
          ...
        />
        <template v-else>
          {{ renderCell(item, cell) }}
        </template>
      </td>
    </tr>
  </tbody>
</template>

如果你想让它更通用,你可以使用v-bind做一些事情:

<template>
  <tbody>
    <tr v-for="item in data">
      <td v-for="cell in cells">
        <component
          v-if="cell.content"
          v-bind="cell.content(item)"
        />
        <template v-else>
          {{ renderCell(item, cell) }}
        </template>
      </td>
    </tr>
  </tbody>
</template>

在这种情况下, cell.content需要返回一个合适的对象而不是一个字符串,如下所示:

formatCells(){
  return [
    { path: 'id', label: 'Id'},
    { path: 'date', label: 'Date'},
    { path: 'damage', label: 'Damage'},
    { key: 'option', content: purchase => ({ is: 'table-row-options', title: 'Options', ... })
  ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM