Javier Villanueva
Javier Villanueva

Reputation: 4058

Vue only renders first custom component issue

I have a simple Vue app where I'm trying to render multiple custom components, here's what I'm trying:

JS

Vue.component('refinement-list', {
  props: ['attribute', 'title'],
  template: '<div>{{attribute}} - {{title}}</div>'
});

new Vue({
  el: '#app'
});

HTML

<div id="app">
  <refinement-list attribute="test" title="Test" />
  <refinement-list attribute="sample" title="Sample" />
</div>

However the problem is that only the first component is rendered, see working example: https://codepen.io/javiervd/pen/vYBpQMm

I tried registering the component locally instead but no luck. I'm also using Vue with a script tag in my app because I can't use a build system for this particular project, not sure if that matters.

Can anyone point me in the right direction? Thanks.

Upvotes: 2

Views: 1084

Answers (3)

Eric McCormick
Eric McCormick

Reputation: 2733

I forked your codepen and can confirm this is working with the separate closing tag style, in place of using self-closing tags for the components.

<div id="app">
  <refinement-list attribute="test" title="Test"></refinement-list>
  <refinement-list attribute="sample" title="Sample"></refinement-list>
</div>

ref: https://codepen.io/edm00se/pen/pozpqym?editors=1010

The self-closing tag versus (full?) closing tag is discussed in the vue style guide page (v2) and it is expressed that for string templates (as I suspect codepen is doing when loading your HTML content), to use the closing tag, while self-closing are fine in single-file components, JSX, and string templates (things which are processed during build and component names are better known).

Upvotes: 2

Matt
Matt

Reputation: 44058

Since you are defining the template in the DOM, you can't use self-closing tags for the custom components.

This should work:

<div id="app">
  <refinement-list attribute="test" title="Test"></refinement-list>
  <refinement-list attribute="sample" title="Sample"></refinement-list>
</div>

This limitation doesn't exist in template strings or Single File Components.

You can read more about this here: https://v2.vuejs.org/v2/style-guide/#Self-closing-components-strongly-recommended

Upvotes: 7

Tony Tom
Tony Tom

Reputation: 1583

You should give like this in the HTML section if you want to use the self-closing tags. But it's not recommended for DOM Templates

<div id="app">
  <div>
  <refinement-list attribute="test" title="Test1" />
  </div>
  <div>
  <refinement-list attribute="test" title="Test2" />
  </div>
</div>

enter image description here

Upvotes: 3

Related Questions