鍍金池/ 問答/HTML/ vue動(dòng)態(tài)獲取子元素個(gè)數(shù)

vue動(dòng)態(tài)獲取子元素個(gè)數(shù)

組件A :
輸出名為test:

<template>
    <div ref="wrapper">
      <ul ref="itemWrapper">
        <slot></slot>
      </ul>
    </div>
</template>

組件B:dom結(jié)構(gòu)如下,li是獲取數(shù)據(jù)之后渲染的

<test class="wrapper" ref="wrapper" :data="discList">
    <li v-for="item in discList" class="item">
        <div class="icon">
            <img alt="專輯圖片" v-lazy="item.imgurl">
        </div>
        <div class="text">
            <h2 class="name" v-html="item.creator.name"></h2>
            <span class="desc" v-html="item.dissname"></span>
        </div>
    </li>
</test>

在組件A中:
methods中定義了一個(gè)方法

_getItemLength() {
    let children = this.$refs.itemWrapper.children;
    console.log(children.length);
    return children.length;
}

然后再mounted中調(diào)用

mounted() {
    setTimeout(() => {
        this._getItemLength()
    }, 20);
}

這樣獲取到的數(shù)量是不對(duì)的,要怎樣才能正確獲取到子元素的數(shù)量。

回答
編輯回答
假灑脫

為什么要這樣取呢 直接this.discList.length不好嗎

2018年7月31日 02:15
編輯回答
久愛她
computed: {
  ItemLength() {
    return this.discList.length
  }
}
2017年12月28日 12:26