账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    vue循环组件key报警告
    26
    0

    vue循环组件,数据从后台请求回来,就会出现如下报错,若将数据写死,不从后台请求,又不会。

    [Vue warn]: Avoid using non-primitive value as key, use string/number value instead.
    
    found in
    
    ---> <ArticleBlock>
           <Home> at src/views/index/Home.vue
             <App> at src/App.vue
               <Root>

    这边是我循环组件的代码

        <template v-for="(item, index) in articleList">
            <ArticleBlock :article="item" :key="index"/>
        </template>

    ArticleBlock的代码

    <template>
      <div class="l-article-block">
        <h3 class="o-article-title"><router-link :to="{name: 'detail', params: {id: article.id}}">{{article.title}}</router-link></h3>
        <div class="l-article-info">
          <ul class="flex">
            <li class="flex-center">
              <i class="iconfont icon-shijian"></i>
              <span class="o-info-desc">{{article.createdAt | formatToYMD}}</span>
            </li>
            <li class="flex-center">
              <i class="iconfont icon-biaoqian"></i>
              <span class="o-label-item" v-for="item in article.labels" :key="item">{{item.name}}</span>
            </li>
          </ul>
        </div>
        <section class="l-article-profile" v-html="article.profile"></section>
        <div class="o-more">
          <router-link :to="{path: '/detail', query: {id: article.id}}">阅读更多 ></router-link>
        </div>
      </div>
    </template>
    
    <script>
    export default {
      name: 'article-block',
      props: {
        article: {
          type: Object,
          required: true
        }
      },
      components: {},
      filters: {
        formatToYMD (rawDate) {
          const date = new Date(rawDate)
          const year = date.getFullYear()
          const month = (date.getMonth() + 1).toString().padStart(2, '0')
          const day = date.getDate().toString().padStart(2, '0')
          return `${year}-${month}-${day}`
        }
      }
    }
    </script>
    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • l吃味的猫′ⅴ` 普通会员 1楼

      在Vue中,如果你在循环组件中使用key属性,可能会出现警告。这是因为key属性用于在Vue中保持组件的唯一性。当你在循环中使用key属性时,Vue会根据你给定的key来生成一个唯一的标识符。

      如果你的循环组件的key属性在循环的某个位置出现了错误,Vue可能会报错。例如,如果你的循环组件在循环体中没有使用key属性,那么Vue可能会报错告诉你TypeError: Cannot read property 'key' of undefined

      为了避免这种错误,你应该确保你的循环组件在循环体中使用了key属性。你可以这样做:

      javascript export default { props: { data: { type: Array, required: true, }, }, methods: { // ... }, };

      这样,Vue就会在每个循环元素中生成一个唯一的key,从而避免了key属性在循环中出现错误的问题。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部