The template root disallows v for directives vue valid template root

Can anyone help me please I am so fed with searching online for it everywhere

<template> <div class="post" v-for="post" in posts > <div><strong>Title</strong>{{post.title}}</div> <div><strong>Desctiption</strong>{{post.body}}</div> </div>
</template>
<script>
export default{ data(){ return{ posts:[ { id: 1, title: 'javascript', body: "the desctiption"}, { id: 2, title: 'javascript2', body: "the desctiption"}, { id: 3, title: 'javascript3', body: "the desctiption"}, ] } }
}

На самом деле это три проблемы в одной:

Может ли кто-нибудь помочь мне, пожалуйста, мне так надоело искать его везде в Интернете

 enter code 
"eslint-eslint: the template root disallows v-for directives"

How am I supposed to loop and render each post?

<related-post-list :relatedBehaviourPost= {{ $relatedBehaviourPosts }}></>
<template>
<div class="sidebar_related_content_container" v-for="behaviour in relatedBehaviourPosts " :key="behaviour.id" style=""> <a class="sidebar_related_content_image" data-hren="/conducta-canina/{{ relatedBehaviour.slug }}" style="background-image:url('{{ behaviour.image }}');"> <div class="black_gradient" style=""></div> </a> <div class="sidebar_related_content_text_container" style=""> <span class="sidebar_related_content_text_title" style="">{{ behaviour.postcategory.name }}</span> <span class="sidebar_related_content_text_description" style="">{{ behaviour.title }}</span> </div>
</div>
</template>
<!--SCRIPTS-->
<script> export default { props: ['relatedBehaviourPosts'], data: function () { return { //data } }, mounted() { console.log('Footer mounted.') } }
</script>
<!--STYLES-->
<style scoped>
</style>

Я пытаюсь создать простой компонент списка сообщений, в котором я использую директиву v-for, но вижу следующую ошибку:

"eslint-eslint: the template root disallows v-for directives"

Как я должен зацикливать и отображать каждое сообщение?

<related-post-list :relatedBehaviourPost= {{ $relatedBehaviourPosts }}></>
<template>
<div class="sidebar_related_content_container" v-for="behaviour in relatedBehaviourPosts " :key="behaviour.id" style=""> <a class="sidebar_related_content_image" data-hren="/conducta-canina/{{ relatedBehaviour.slug }}" style="background-image:url('{{ behaviour.image }}');"> <div class="black_gradient" style=""></div> </a> <div class="sidebar_related_content_text_container" style=""> <span class="sidebar_related_content_text_title" style="">{{ behaviour.postcategory.name }}</span> <span class="sidebar_related_content_text_description" style="">{{ behaviour.title }}</span> </div>
</div>
</template>
<!--SCRIPTS-->
<script> export default { props: ['relatedBehaviourPosts'], data: function () { return { //data } }, mounted() { console.log('Footer mounted.') } }
</script>
<!--STYLES-->
<style scoped>
</style>

После создания проекта Vue 3 я заметил ошибку в моем App.vue.

A functional component that renders the matched component for the given path. Components rendered in can also contain its own , which will render components for nested paths.
API Reference
[vue/no-multiple-template-root]
The template root requires exactly one element.eslint-plugin-vue

Я пробовал поставить

 "vue/no-multiple-template-root": 0

В моем .eslintrc.js

Но ошибка остается. Как мне избавиться от ошибки? Поскольку в Vue 3 вам не обязательно иметь только один элемент в шаблоне.

module.exports = { root: true, env: { node: true }, extends: [ "plugin:vue/vue3-essential", "eslint:recommended", "@vue/typescript/recommended", "@vue/prettier", "@vue/prettier/@typescript-eslint" ], parserOptions: { ecmaVersion: 2020 }, rules: { "no-console": process.env.NODE_ENV === "production" ? "warn" : "off", "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off", "vue/no-multiple-template-root": 0 }
};

Tell us about your environment

  • ESLint version: 6.6.0
  • eslint-plugin-vue version: 6.0.0
  • Node version: 13.0.1

Please show your full configuration:

module.exports = { root: true, env: { browser: true, node: true }, parserOptions: { parser: 'babel-eslint' }, extends: [ '@nuxtjs', 'prettier', 'prettier/vue', 'plugin:prettier/recommended', 'plugin:nuxt/recommended' ], plugins: [ 'prettier' ], // add your custom rules here rules: { 'vue/no-v-html': 'off' }
}

What did you do?

<template> <div v-if="status === 'LOADING'" class="d-flex justify-content-center loading" > Loading comments <span class="one">.</span> <span class="two">.</span> <span class="three">.</span> </div> <div v-else-if="status === 'LOADED'"> <h4 class="comments-head"> <font-awesome-icon :icon="['far', 'comments']" class="mx-2" /> {{ `${commentsCount} comment${commentsCount > 1 ? 's' : ''}` }} </h4> <div v-for="comment in comments" :key="comment.id" class="comment"> <div class="meta"> <span class="author">{{ comment.author.username }}</span> on <time :datetime="comment.publishedAt" class="date"> {{ comment.publishedAt | formatDate }} </time> </div> <div v-html="comment.content" class="content"></div> </div> <div v-if="comments.length === 0" class="no-comments text-center py-3"> There are no comments. </div> <b-pagination v-if="comments.length > 0" v-model="page" :total-rows="commentsCount" :per-page="perPage" size="sm" align="center" ></b-pagination> <div v-if="$auth.loggedIn" class="add-comment"> <b-form v-if="['WAITING', 'SENDING'].includes(newCommentStatus)" @submit.prevent.stop="addComment" > <h4 class="comments-head"> Add a comment </h4> <classic-editor id="new-comment-body" v-model="newCommentContent" :config="{ toolbar: ['bold', 'italic'], readOnly: true }" :disabled="newCommentStatus === 'SENDING'" ></classic-editor> <div class="mt-3 d-flex justify-content-end"> <b-button :disabled=" newCommentStatus === 'SENDING' || newCommentContent.length === 0 " variant="primary" type="submit" > <font-awesome-icon v-if="newCommentStatus === 'SENDING'" icon="spinner" spin class="mr-2" /> Send </b-button> </div> </b-form> <b-alert :show="newCommentStatus === 'SENT'" variant="success"> Your comment has been successfully added. </b-alert> <b-alert :show="newCommentStatus === 'ERROR'" variant="danger"> {{ newCommentErrorMessage }} </b-alert> </div> </div>
</template>

What did you expect to happen?

This code does not trigger an error

What actually happened?

The vue/valid-template-root rule throws an error. This exact same code was working on ESLint 5 / eslint-plugin-nuxt 5.2.3, and I’m seeing nothing in the changelog that could explain why it’s not working anymore.

components\poll\Comments.vue
12:3 error The template root requires exactly one element vue/valid-template-root

Ответа

Vue.js должен иметь единственный элемент в корне шаблона. Если у вас есть директива, при заполнении DOM в корне будет несколько элементов, что не позволяет Vue.

Так что вам просто нужно добавить еще один
<div> элемент, чтобы окружить ваш
v-for div.

 <template> <div> <div class="post" v-for="post in posts" :key="post.id"> <div><strong>Title</strong>{{post.title}}</div> <div><strong>Desctiption</strong>{{post.body}}</div> </div> </div>
</template>

В vue two вы должны иметь один корневой элемент, использование цикла v-for будет отображать несколько элементов в шаблоне, например:

  <div class="post" > ... </div> <div class="post" > ... </div>

чтобы избежать этого, добавьте дополнительный div и привязайте ключ к идентификатору сообщения
:key="post.id":

 <template>
<div class="posts"> <div class="post" v-for="post in posts" :key="post.id"> <div><strong>Title</strong>{{post.title}}</div> <div><strong>Desctiption</strong>{{post.body}}</div> </div>
</div>
</template>

2 ответа

В итоге я отключил Vetur Linting. Vetur считает, что это проект Vue 2, поскольку он находится в рабочей области VS Code.

Вы можете решить эту проблему, выполнив

F1>Preferences:Open Settings (JSON)
"vetur.validation.template": false,
"vetur.validation.script": false,
"vetur.validation.style": false,

18 Ноя 2020 в 21:46

2 ответа

<template> <div> <!-- single root element here --> <div v-for="behaviour in relatedBehaviourPosts " :key="behaviour.id"> <!-- ... --> </div> </div>
</template>

Также обратите внимание, что Vue 2 не поддерживает интерполяцию строк в привязках атрибутов, поэтому их необходимо заменить привязками данных этого синтаксиса:

:ATTRIBUTE_NAME="VALUE"

В частности, замените это:

<a data-hren="/conducta-canina/{{ behaviour.slug }}" style="background-image:url('{{ behaviour.image }}');"></a> <!-- DON'T DO THIS -->

С этим (используя литералы шаблона ES2015):

<a :data-hren="`/conducta-canina/${behaviour.slug}`" :style="`background-image:url('${behaviour.image}');`"></a>

Или с этим (используя конкатенацию строк):

<a :data-hren="'/conducta-canina/' + behaviour.slug" :style="'background-image:url(\'' + behaviour.image + '\');'"></a>

Демо Vue 2

Обратите внимание, что Vue 3 допускает несколько корневых узлов, поэтому ваш шаблон компонента будет работать там.

15 Июл 2022 в 22:49

Иногда я получал эту ошибку, проблема в том, что корень шаблона не допускает директивы v-for. Решение использовать директивы в шаблоне заключается в том, что вам необходимо предоставить корневой div, содержащий элемент, содержащий ваши директивы. В моем случае это сработало. Дополнительную информацию см. Здесь https://eslint.vuejs.org/rules/valid -template-root.html

<template>
<!-- place a root element -->
<div> <div v-for='item in menu'>some items</div>
</div>
</template>

24 Июл 2020 в 15:33

Дополнительно:  Root права на android sony xperia с
Оцените статью
Master Hi-technology