0
votes

Good evening, everyone,

I have a vue-template which should generate a table. The table header, more precisely the number of individual column headers can be determined dynamically via the "slots".

Unfortunately there is always the error that there can only be one root element.

How can I - as easy as possible - make sure that my components are inserted into the header anyway.

table.vue

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

And this ist how i would like to use it:

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

Here the error-message: Cannot use slot as component root element because it may contain multiple nodes.

Edit:

Here you can find the example: https://codesandbox.io/s/small-waterfall-k6fit

1
could you make the tr element be the slot?aprouja1
It's the same error. It seems to be due to the fact that tables are treated a bit special here.Björn K.
Please post a sample of the code. Running on COdeSandbox doesnt throw an error: codesandbox.io/s/…aprouja1
why do you want to use slots for this? would a v-for be cleaner/easier if the contents are just text?depperm
Unfortunately, I cannot reproduce the error with codesandbox. But I don't use Vue.js with node.js either, just include the javascript file.Björn K.

1 Answers

1
votes

Try this! You just need to wrap <th> with <template> tag.

<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>