vue父子组件中this.$children得不到数组?

vue父子组件中this.children得不到数组,但是vm.children可以,this.$children.length=0?


<script>

Vue.component('my-item',{

  props:['type','price'],

  template:'<div>{{type}}价格:{{price}}<input type="button" name="" value="购买" @click="goumai">购买的数量:{{amount}}</div>',

  data(){

    return {

      amount:0

    }

  },

  methods:{

    goumai(){

      this.amount++;

    }

  }

})


let vm = new Vue({

  el : '#app',

  computed:{

    total(){

      console.log(this.$children.length);

      var sum = 0;

      for(var i=0;i < this.$children.length;i++){

        sum+=this.$children[i].amount*this.$children[i].price;

      }

      return sum;

    }

  }

})

</script>


偶然的你
浏览 1560回答 1
1回答

慕尼黑8549860

computed应该是在遍历数据的阶段生成,而那个时候my-item还没有被挂在到父组件上...created () {&nbsp; &nbsp; console.log(this.total)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// sum&nbsp; &nbsp; console.log(this.$children)&nbsp; &nbsp; &nbsp; &nbsp;// Array[]},mounted () {&nbsp; &nbsp; console.log(this.total)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// sum&nbsp; &nbsp; console.log(this.$children)&nbsp; &nbsp; &nbsp; &nbsp;// Array[Object]}...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript