英文:
Why can't my table component render the value processed by the render function passed in?
问题
在Vue3中,我想动态渲染我的表格,但没有生效
我定义了一个表格组件
<script setup>
const props = defineProps({
columns: {
type: Array,
default: () => [],
required: true,
},
data: {
type: Array,
default: () => [],
required: true
}
})
</script>
<template>
<table class="table__container">
<thead>
<tr>
<th v-for="column in columns" :key="column.key">{{ column.title }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in data" :key="index">
<td v-for="column in columns" :key="column.key">
<span v-if="column.render">
{{ column.render(item) }}
</span>
<span v-else>{{ item[column.key] }}</span>
</td>
</tr>
</tbody>
</table>
</template>
我将columns
传递给了表格组件,
const columns = [
{
title: '歌曲',
key: 'name'
},
{
title: '歌手',
key: 'singer'
},
{
title: '专辑',
key: 'album'
},
{
title: '时长',
key: 'duration',
render: (row) => {
const { duration } = row;
return h(
'span',
{},
formatDuration(duration)
);
}
}
]
但是v-if="column.render"
没有生效,并且控制台报错 Uncaught (in promise) TypeError: Converting circular structure to JSON --> starting at object with constructor 'Object' | property 'vnode' -> object with constructor 'Object' --- property 'component' closes the circle at JSON.stringify (
英文:
In Vue3 , I want to dynamically render my table , but did not take effect
I defined a table component
<script setup>
const props = defineProps({
columns: {
type: Array,
default: () => [],
required: true,
},
data: {
type: Array,
default: () => [],
required: true
}
})
</script>
<template>
<table class="table__container">
<thead>
<tr>
<th v-for="column in columns" :key="column.key">{{ column.title }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in data" :key="index">
<td v-for="column in columns" :key="column.key">
<span v-if="column.render">
{{ column.render(item) }}
</span>
<span v-else>{{ item[column.key] }}</span>
</td>
</tr>
</tbody>
</table>
</template>
I passed columns to the table component ,
const columns = [
{
title: 'song',
key: 'name'
},
{
title: 'singer',
key: 'singer'
},
{
title: 'album',
key: 'album'
},
{
title: 'duration',
key: 'duration',
render:(row) => {
const { duration } = row;
return h(
'span',
{},
formatDuration(duration)
);
}
}
]
but v-if = 'column.render' doesn't take effect, and console error
Uncaught (in promise) TypeError: Converting circular structure to JSON
--> starting at object with constructor 'Object'
| property 'vnode' -> object with constructor 'Object'
--- property 'component' closes the circle
at JSON.stringify (<anonymous>)
How can I fix it?
答案1
得分: 1
你可以尝试使用 <component>
<span v-if="column.render">
<component :is="column.render(item)"></component>
</span>
英文:
You can try using <component>
<span v-if="column.render">
<component :is="column.render(item)"></component>
</span>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论