【问题标题】:If you are using v-if on multiple elements, use v-else-if to chain them instead. Laravel + VueJs如果您在多个元素上使用 v-if,请改用 v-else-if 链接它们。 Laravel + VueJs
【发布时间】:2018-05-29 12:49:18
【问题描述】:

第一个问题 - How to create components in a loop?

在我的 Index.vue 中有一个循环

<div v-for="(image, id, index) in images" class="col-md-4">
  <photo :src ="image.src" :symbolId="image.id" :photoId="image.photo_id" :index="index"></photo>
</div>

在我的 app.js 中我注册了一个组件

Vue.component('photo',
   require('./components/Photo.vue')
);

在我的 Photo.vue 中

<template>
    <img v-on:click="replaceImages()" :src="src" class="img-responsive image" :data-symbol-id="symbolId" :data-photo-id="photoId">
<input :name="index" :data-symbol-id="symbolId" :data-photo-id="photoId" 
type="hidden" :value="src">
</template>

<script>
export default {
    name: 'photo',
    props: {
        src: {
            type : String,
            required: true
        },
        symbolId: {
            type: String,
            required: true
        },
        photoId: {
            type: Number,
            required: true
        },
        index: {
            type: Number,
            required: true
        }
    },
}
</script>

但是当 npm 编译它时,我得到一个错误

组件模板应该只包含一个根元素。如果您在多个元素上使用 v-if,请改用 v-else-if 链接它们。

【问题讨论】:

    标签: laravel-5 vue.js


    【解决方案1】:

    添加一个div代替模板,Vue期望一个包含所有模板的根元素,如果使用如下示例,则vue省略模板标签

    <template>
    <div>
        <img v-on:click="replaceImages()" :src="src" class="img-responsive image" :data-symbol-id="symbolId" :data-photo-id="photoId">
    <input :name="index" :data-symbol-id="symbolId" :data-photo-id="photoId" 
    type="hidden" :value="src">
    </div>
    </template>
    

    var child = {
      template : '<div>Child component</div>'
    }
    var app = new Vue({
      el:"#app",
      components:{
        child
      },
      data:{
        name:''
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.js"></script>
    <div id="app">
    <child></child>
    </div>

    【讨论】:

    • 谢谢!但是在对 div 进行简单的添加之后,一切都正常了!没有 var 孩子。 joxi.ru/LmGakZYueXEL6A
    • @Виктор : 是的,我说Add one div instead template, Vue expect one root element which contain all template
    • 我可以用 span 代替 div 吗?
    • @Виктор : 将您的标题更改为Getting error in vue : Component template should contain exactly one root element 以便他人识别
    猜你喜欢
    • 2018-04-23
    • 2021-11-25
    • 2021-05-18
    • 2019-01-03
    • 2017-12-21
    • 2022-01-23
    • 2021-02-21
    • 2018-05-10
    • 2021-12-27
    相关资源
    最近更新 更多