【问题标题】:Has anyone came across this problem? [vue/no-multiple-template-root] The template root disallows 'v-for' directives.eslint-plugin-vue有没有人遇到过这个问题? [vue/no-multiple-template-root] 模板根不允许 'v-for' 指令.eslint-plugin-vue
【发布时间】:2021-10-22 15:10:28
【问题描述】:

其实是三题合一:

[vue/no-multiple-template-root] 模板根不允许'v-for'指令。eslint-plugin-vue

[vue/无解析错误] 解析错误:应为别名,但为空。eslint-plugin-vue

[vue/valid-v-for] 预期 'v-bind:key' 指令使用由 'v-for' 指令定义的变量。eslint-plugin-vue

谁能帮帮我,我已经厌倦了在网上到处搜索它

enter code 

<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"},
      ]
    }
  }
}

【问题讨论】:

    标签: vue.js vue-directives


    【解决方案1】:

    Vue.js 必须在模板的根部有一个元素。如果你有一个v-for 指令,当填充 DOM 时,根会出现多个 &lt;div&gt; 元素,这是 Vue 不允许的。

    所以你只需要添加另一个&lt;div&gt; 元素来包围你的v-for div。

    然后,将 in posts 移动到引号中并添加 :key

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

    【讨论】:

      【解决方案2】:

      在 vue 2 中你应该有一个根元素,使用 v-for 循环会在模板中渲染多个元素,例如:

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

      为避免这种情况,请添加一个额外的 div 并将密钥绑定到帖子 ID :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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-12
        • 2021-02-28
        • 2021-10-13
        • 2021-06-22
        • 2020-01-25
        • 2020-10-09
        • 2020-04-27
        • 2022-01-22
        相关资源
        最近更新 更多