【问题标题】:How to use <th> as slot in vue.js如何在 vue.js 中使用 <th> 作为插槽
【发布时间】:2020-04-22 12:55:38
【问题描述】:

大家晚上好

我有一个应该生成表格的 vue 模板。表头,更准确地说是单个列头的数量可以通过“槽”动态确定。

不幸的是,总是存在只能有一个根元素的错误。

我怎样才能 - 尽可能简单 - 确保我的组件无论如何都插入到标题中。

table.vue

<template>
  <table>
    <thead>
      <tr>
        <slot></slot>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
    </tbody>
  </table>
</template>

这就是我想如何使用它:

<lbtable>
  <th>Column 1</th>
  <th>Column 2</th>
</lbtable>

这里是错误消息:不能使用插槽作为组件根元素,因为它可能包含多个节点。

编辑:

您可以在此处找到示例: https://codesandbox.io/s/small-waterfall-k6fit

【问题讨论】:

  • 你能让tr元素成为槽吗?
  • 同样的错误。这似乎是因为这里的表格被处理得有点特殊。
  • 请发布代码示例。在 COdeSandbox 上运行不会抛出错误:codesandbox.io/s/…
  • 为什么要为此使用插槽?如果内容只是文本,v-for 会更干净/更容易吗?
  • 不幸的是,我无法使用代码和框重现该错误。但我也不将 Vue.js 与 node.js 一起使用,只包含 javascript 文件。

标签: vue.js vuejs2 vue-component


【解决方案1】:

试试这个!你只需要用&lt;template&gt;标签包裹&lt;th&gt;

<html>
<head>
	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
	 <lbtable>
		<template>
	            <th>Column 1</th>
		    <th>Column 2</th>
		</template>
	</lbtable>
  </div>
</body>
</html>
<script>
	Vue.component('lbtable', {
	'template': `
	   <div>
		<table border="1">
			<thead>
			   <tr>
			     <slot></slot>
			   </tr>
			</thead>
			<tbody>
			<tr>
			   <td>1</td>
		       <td>2</td>
			</tr>
			</tbody>
		</table>
	   </div>`});

	new Vue({
		el: "#app"
	});
</script>

【讨论】:

  • 嗯,这在 Chrome 和 FF 中有效,但在 IE 中无效——因为 IE 不支持模板文字。所以我们需要在vue-loader中使用single-file-components,然后就不行了。
猜你喜欢
  • 2021-05-17
  • 2019-05-25
  • 2020-11-15
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 2020-06-05
  • 2019-07-08
  • 1970-01-01
相关资源
最近更新 更多