如何从字符串渲染vuejs组件

时间:2019-06-24 09:26:15

标签: vue.js

我有一个vue组件,该组件创建一个具有4 td的表主体,第一个td捕获ID,然后分别捕获日期,项目和选项按钮。我能够显示数据,但是选项按钮显示为字符串而不是显示为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)
        }
    }
}

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

1 个答案:

答案 0 :(得分:0)

最佳解决方案将取决于您所需的通用性。您可以使用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', ... })
  ]
}
相关问题