当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue中子组件的methods中获取到props中的值方法

vue中子组件的methods中获取到props中的值方法

2018年09月23日  | 移动技术网IT编程  | 我要评论

原始社会生存记,北京大中电器网上商城,尸王横行

父子组件通信

这个官网很清楚,也很简单,父组件中使用v-bind绑定传送,子组件使用props接收即可

例如:

父组件中

<template>
  <div>
    <head-top></head-top>
    <section class="data_section">
      <header class="chart-title">数据统计</header>
      <el-row :gutter="20" class="chart-head">
        <el-col :xs="24" :sm="12" :md="6" :lg="6"><div class="grid-content data-head blue-head">统计:</div></el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6"><div class="grid-content data-head">销售数量 <span>{{number}}</span></div></el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6"><div class="grid-content data-head">销售金额 <span>{{amount}}</span></div></el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6"><div class="grid-content data-head">利润统计 <span>{{profits}}</span></div></el-col>
      </el-row>
    </section>
    <chart :chartdata="chartdata"></chart>
  </div>
</template>

<script>
  data(){
      return {
        number: null,
        amount: null,
        profits: null,
        chartdata: [10,10,10]
      }
    },
</script>

子组件中

export default {
  props: ['chartdata']
}

这种情况下,子组件的methods中想要取到props中的值,直接使用this.chartdata即可

但是有写情况下,你的chartdata里面的值并不是固定的,而是动态获取的,这种情况下,你会发现methods中是取不到你的chartdata的,或者取到的一直是默认值

比如下面这个情况

父组件中

<script>
  data(){
      return {
        number: null,
        amount: null,
        profits: null,
        chartdata: []
      }
    },
    mounted(){
      this.getstatistics();
    },
    methods: {
      //获取统计数据
      getstatistics(){
        console.log('获取统计数据')
        axios.post(api,{

        }).then((res) => {
          this.number = res.data.domain.list[0].number;
          this.amount = res.data.domain.list[0].amount;
          this.profits = res.data.domain.list[0].profits;
          this.chartdata = [this.number,this.amount,this.profits];
        }).catch((err) => {
          console.log(err);
        })
      },
    },
</script>

此时子组件的methods中使用this.chartdata会发现是不存在的(因为为空了)

这情况我是使用watch处理

解决方法如下:

使用watch

props: ['chartdata'],
    data(){
      return {
        cdata: []
      }
    },
    watch: {
      chartdata: function(newval,oldval){
        this.cdata = newval; //newval即是chartdata
        this.drawchart();
      }
    },

监听chartdata的值,当它由空转变时就会触发,这时候就能取到了,拿到值后要做的处理方法也需要在watch里面执行

以上这篇vue中子组件的methods中获取到props中的值方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网