Vue JS - Rendering Multiple Instances of Components

纵然是瞬间 提交于 2020-08-10 07:18:26

问题


Development Environment:

First, I am using Vue 1.0 and Vueify 7.0.0 using the latest node. js, npm and browserify to compile the code on an Ubuntu machine with a local Apache Server.

The Problem:

I have created a custom component for <form-input/> which renders without an error. However, when trying to place them next to each other only one will render:

<form>
      <form-input />
      <form-input />
      <form-input />
</form>

In order to get multiple components to render I have to wrap each one in it's own <div>.

<form>
      <div><form-input /></div>
      <div><form-input /></div>
      <div><form-input /></div>
</form>

For reference the <form-input /> template looks like this:

<template>
    <div class="input-group">
        <label"></label>
        <input name="" class="form-control" type="text">
    </div>
</template>

Not that it's a terribly bad problem, but it's so much easier to read without the extra <div> tags.

Question:

Is this expected behavior because each component needs its own dom element to bind to or am I missing something?

FYI:

I have also tried wrapping the template with an extra div tag, but that didn't help. I also do not get any compile or runtime errors either way it writes the template.

Thanks in advance.


回答1:


I am not sure if this could be causing the issue, but self-closing tags are not recommended by the creator of Vue.js: https://github.com/vuejs/vue/issues/1036. Do you still have an issue if you change the inputs to <form-input></form-input>?




回答2:


I don't know how this advise will work with Vue 1.0, but with Vue 2.0 this works fine:

  • you just need to add for each component the key attribute which tells Vue to render these custom components as separate components.
<form>
   <form-input key="form-input-1" />
   <form-input key="form-input-2" />
   <form-input key="form-input-3" />
</form>


来源:https://stackoverflow.com/questions/34560374/vue-js-rendering-multiple-instances-of-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!