Vue 2加载组件4次

时间:2017-07-07 16:57:19

标签: javascript chart.js vuejs2 vue-component vue-chartjs

当我尝试使用VueCharts加载组件时,组件加载四次。我怎么解决这个问题?因为我需要在组件加载时发出ajax请求并且请求重要

  

**编辑**

import { Line } from 'vue-chartjs'
import Const from '../helper/const.js'

const URL = Const.ANALYTIC_SENTIMENT

export default Line.extend({
  props: ['idBot', 'initialDate', 'finalDate'],
  data () {
    return {
      consulta: [],
      datacollection: {
        labels: [],
        datasets: []
      },
      cores: ['#ff0000', '#ff4300', '#ff7b00', '#ffae00', '#c19403', '#ffe100', '#aeff00', '#6aff00', '#26ff00', '#2fa803', '#03c107'],
      moment: require('moment')
    }
  },
  methods: {
    dateFormat: function (date) {
      this.moment.locale('pt-BR')
      return this.moment(date).format('L')
    },
    graphGenerator: function () {
      let self = this

      this.renderChart({
        labels: this.datacollection.labels,
        datasets: this.datacollection.datasets
      }, {
        responsive: true,
        maintainAspectRatio: false,
        // Click event
        onClick: function (e) {
          let activePoints = this.getElementAtEvent(e)

          if (activePoints.length > 0) {
          // Dados do Gŕafico
            let chartData = activePoints[0]['_chart'].config.data

          // Index do DataSet do Ponto
            let dsidx = activePoints[0]['_datasetIndex']

            // Index do Ponto
            let idx = activePoints[0]['_index']

          // Label do Ponto
            let date = chartData.labels[idx]

          // Valor do Sentimento no Gráfico
            let sentiment = chartData.datasets[dsidx].label

            self.$emit('emit', {'date': date, 'sentiment': sentiment})
            console.log('date: ' + date + 'sentiment: ' + sentiment)
          }
        },
        legend: {
          position: 'right',
          fullWidth: true,
          labels: {
            boxWidth: 50,
            fontSize: 16
          }
        },
        title: {
          display: true,
          text: 'Sentimento',
          fontSize: 25
        },
        tooltips: {
          mode: 'index',
          intersect: false
        },
        hover: {
          mode: 'nearest',
          intersect: true
        },
        scales: {
          xAxes: [{
            display: true,
            ticks: {
              beginAtZero: true
            },
            scaleLabel: {
              display: true,
              labelString: 'Mês',
              fontSize: 25
            }
          }],
          yAxes: [{
            display: true,
            ticks: {
              beginAtZero: true
            },
            scaleLabel: {
              display: true,
              labelString: 'Total',
              fontSize: 25,
              fontColor: 'green'
            }
          }]
        }
      })
    },
    loadData: function () {
      this.datacollection.labels = []
      this.datacollection.datasets = []
      let datasets = []

      for (var i = 0; i <= 10; i++) {
        let linha = {
          label: i,
          backgroundColor: this.cores[i],
          fill: false,
          tension: 0.1,
          borderColor: this.cores[i],
          pointBorderColor: '',
          pointBorderWidth: 5,
          // Dados da Linha
          data: []
        }
        datasets.push(linha)
      }
      let entrouGeral = []
      this.consulta.forEach((dado, index) => {
        this.datacollection.labels.push(this.dateFormat(dado.key))
        let entrou = []
        dado.feeling.buckets.forEach((sentiment) => {
          entrou.push(sentiment.key)
          datasets[sentiment.key].data.push(sentiment.doc_count)
        })

        entrou.forEach((element) => {
          if (!entrouGeral.includes(element)) {
            entrouGeral.push(element)
          }
        })

        datasets.forEach((teste, index) => {
          if (!entrou.includes(index)) {
            teste.data.push('*')
          }
        })
      })

      for (let i = 0; i < datasets.length; i++) {
        if (entrouGeral.includes(datasets[i].label)) {
          this.datacollection.datasets.push(datasets[i])
        }
      }
    },
    async apiCall () {
      let url = URL + this.idBot

      if (this.initialDate !== 'Invalid date' && this.finalDate !== 'Invalid date') {
        url += `?initialDate=${this.initialDate}&finalDate=${this.finalDate}`
        console.log(url)
      }

      this.$emit('load', true)

      await this.$http.get(url).then((res) => {
        this.consulta = res.data

        this.loadData()
      }).then(() => {
        this._chart.data = this.datacollection
        this._chart.update()
        this.$emit('load', false)
      }, (res) => {
        console.log(res)
      })
    }
  },
  async mounted () {
    this.$emit('load', true)
    await this.$http.get(URL + this.idBot).then((res) => {
      this.consulta = res.data

      this.loadData()

      this.graphGenerator()
    }, (res) => {
      console.log('Resposta: ' + res)
    })
    this.$emit('load', false)
  },
  watch: {
    'finalDate': {
      handler: function () {
        console.log('aa')
        this.apiCall()
      },
      deep: true
    }
  }
})

-----------------------------THE PART WHERE THE COMPONENT IS LOADED ------

   <v-card flat>
          <v-card-text >
            <component class="elevation-3" :is="isSelected" @emit="show" @load="isLoading" :idBot="idBot" :initialDate="initialDate" :finalDate="finalDate"></component>

            <v-dialog v-model="dialog.show" :width="700" persistent>
              <v-card

&GT;

0 个答案:

没有答案