【问题标题】:CoreUI Vue chart pass async props to child not workingCoreUI Vue图表将异步道具传递给不工作的孩子
【发布时间】:2022-01-12 08:25:53
【问题描述】:

我正在尝试将 api 调用中的道具传递给子组件,但它无法正常工作,当我在我的孩子中控制台记录数据时,它会返回具有正确数据的代理对象。但我无法在我想使用它的子组件的 defaultData 计算方法中使用它

父组件

<template>
  <CRow>
    <CCol :md="6" class="mb-4">
      <CCard>
        <CCardHeader>Grafik Pie Hama</CCardHeader>
        <CCardBody><CChartPieExample :labels="labels"/></CCardBody>
      </CCard>
    </CCol>
  </CRow>
</template>

<script>
import * as Charts from './index.js'
import axios from 'axios'

export default {
  name: 'Charts',
  components: {
    ...Charts,
  },
  data() {
    return {
      labels: [],
    }
  },
  methods: {
    async getData() {
      let formdata = new FormData();
      formdata.append("work_location", "1");
      formdata.append("date_from", "2020-01-01");
      formdata.append("date_to", "2021-12-28");
      formdata.append("id_customer", "3");
      formdata.append("id_customer_location", "0");
      const headers = {
        'Authorization': '1cf34c57882bf600d69d9828ee639232KVpR0'
      }
      try {
        await axios.post("https://dev.cleancity.id/api/home/ListResultReportBinatang", formdata, {headers: headers}).then(res => {
          res.data.response.data.map((item) => {
            this.labels.push(item.name_animal)
          })
        });
        
      } catch (error) {
        console.log(error)
      }
    },
  },
  created() {
    this.getData()
  },
}
</script>

子组件

<template>
  <CChartPie :data="defaultData"/>
</template>

<script>
import { CChartPie } from '@coreui/vue-chartjs'
export default {
  name: 'CChartPieExample',
  components: { CChartPie },
  props: ['labels'],

  computed: {
    
    defaultData() {
      
      return {
        labels: this.labels,
        datasets: [
          {
            backgroundColor: ['#41B883', '#E46651', '#00D8FF', '#DD1B16'],
            data: [40, 20, 80, 10],
          },
        ],
      }
    },
  },
  created() {
    // this return proxy object, but unable to use this above in defaultData
      console.log(this.labels)

  },
  
}
</script>

更新:我尝试使用 watch 方法来观察我的标签的变化,现在标签在初始加载时显示,但在我刷新页面/移动到另一个页面后,标签消失了

更新子组件

<template>
  <CChartPie :data="defaultData"/>
</template>

<script>
import { CChartPie } from '@coreui/vue-chartjs'
export default {
  name: 'CChartPieExample',
  components: { CChartPie },
  props: ['labels', 'values'],
  data() {
    return {
      labelsLocal: this.labels,
    };
  },

  watch: {
    labels(val, oldVal) {
      console.log(val)
      if (val !== oldVal) this.labelsLocal = val
    }
  },

  computed: {
    defaultData() {
      
      return {
        labels: this.labelsLocal,
        datasets: [
          {
            backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850", "#734222", "#A52019", "#8A9597", "#DE4C8A", "#F44611", "#999950", "#C51D34", "#382C1E", "#CAC4B0", "#A2231D"],
            data: [40, 20, 80, 10, 10],
          },
        ],
      }
    },
  },

  mounted(){
    console.log(this.labels)
  },
  
}
</script>

【问题讨论】:

标签: javascript vue.js core-ui


【解决方案1】:

您可以使用监视功能更新默认数据。

export default {
    data(){
        return {
            defaultData: {
            }
        }
    }
    watch: {
        labels(newVal, oldVal) {
            this.defaultData = {
                labels: this.labels,
                datasets: [...]
            }
        }
    }
}

【讨论】:

  • 不起作用,如何使用 newVal 和 oldVal 更新标签?
  • 你可以使用 this.labels。它已更新,或者您可以使用 newVal: {labels: newVal}
【解决方案2】:

您是否尝试过使用vm.$watch API?

父组件:

data() {
  return {
    labels: [],
  }
},
methods: {
  async getData() {
     const payload = this.toFormData({
      work_location: '1',
      date_from: "2020-01-01",
      date_to: "2021-12-28",
      id_customer: "3",
      id_customer_location: "0"
    })
    const headers = {
      'Authorization': '1cf34c57882bf600d69d9828ee639232KVpR0'
    }
    try {
      await axios.post("https://dev.cleancity.id/api/home/ListResultReportBinatang", payload, {headers: headers}).then(res => {
        this.labels = res.data.response.data.map(item => item.name_animal)
      });
      
    } catch (error) {
      console.log(error)
    }
  },
  toFormData(rawParams) {
    const params = new FormData()
    if (!this.isObject(rawParams)) return params
  
    const keys = Object.keys(rawParams)
    keys.forEach(key => {
      rawParams[key] !== undefined && params.append(key, rawParams[key])
    })
  
    return params
  },
  isObject(obj) {
    return obj !== null && typeof obj === 'object'
  }
},
mounted() {
  this.getData()
},

子组件

data() {
  return {
    defaultData: {
      labels: [],
      datasets: [
        {
          backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850", "#734222", "#A52019", "#8A9597", "#DE4C8A", "#F44611", "#999950", "#C51D34", "#382C1E", "#CAC4B0", "#A2231D"],
          data: [40, 20, 80, 10, 10],
        },
      ],
    },
  };
},
mounted() {
  const unwatch = this.$watch('labels', function(val) {
    this.$set(this.defaultData, 'labels', val)
    unwatch()
  })
},

【讨论】:

    猜你喜欢
    • 2019-02-03
    • 2020-02-19
    • 2018-05-03
    • 1970-01-01
    • 2020-08-08
    • 2023-03-18
    • 2017-06-03
    • 2018-04-09
    • 2016-03-19
    相关资源
    最近更新 更多