tween не обновляет формат текстовой метки в Vue / D3 - PullRequest
1 голос
/ 03 августа 2020

Я пытался передать код, который отлично работает в простом D3, на Vue. Эта часть кода должна обновлять текст метки столбчатой ​​диаграммы, но не работает. Это data.csv:

country,population
China,2535
India,1654
United States,700
Indonesia,680
Brazil,1785
Total,1821

, а это код для управления гистограммой:

import formatCurrency from '../mixins/formatCurrency';
import formatTime from '../mixins/formatTime';

import {
    select,
    scaleLinear,
    max,
    scaleBand,
    interpolate,
    axisLeft,
    axisBottom,
    forceX,
    csv,
    filter
} from 'd3';


//..
data: () => ({
        dataset: [],
        dataFiltrada: [],
    }),
//..

async mounted() {
        let datos = await csv('/datasets/data.csv')
        this.dataset = Object.freeze(datos)
        //..
        this.graph()
    },
computed: {
    //..
    filtrarData() {
       this.dataFiltrada = this.dataset.filter(d => { return d.country !=='Total'})},
},

methods: {
  graph(){
//..
    const numeros = g.selectAll(this.label).data(this.dataFiltrada)
    numeros
       .enter().append("text")
         .attr("class", this.label)                        
         .attr('x', this.xEtiqueta)
         .attr('y', d => { return -yScale(d.country); })
         .attr('dy', this.yEtiqueta)
         .text(0)                 

      .merge(numeros)
        .transition().duration(this.time)
        .tween(this.label, d => {
             var i = interpolate(1, d.population);
             if (d.population != 0)
             return function(t) {    
                 select(this).text(d => {
                     return (this.label === 'labelg1')                                            
                            ? this.formatCurrency(i(t))
                            : this.formatTime(i(t))
}                                    
//..
mixins: [
        formatCurrency,
        formatTime,
    ],
}

Переходы в порядке, но формат не обновляется. Когда я console.log formatCurrency с любым значением вне функции (t), все в порядке, но внутри области действия функции (t) не работает. Функция formatCurrency выглядит так:

import { format } from 'd3';

export default {
    methods: {
        formatCurrency:(() => {
          var cantNum;
          var formatofinal;
          var simbol = "$";

          function digits_count(n) {
              var count = 0;
              if (n >= 1) ++count;

              while (n / 10 >= 1) {
                  n /= 10;
                  ++count;
              }
              return count;
          };

          function processCantNumAndFormatOfinal(n){
              if (digits_count(n) === 0) {
                  cantNum = 0;
                  formatofinal ='r';
              }
              else if (digits_count(n) === 1) {
                  cantNum = 1;
                  formatofinal ='s';
              }
              else if (digits_count(n) === 2) {
                  cantNum = 2;
                  formatofinal ='s';
              }
              else if (digits_count(n) === 3) {
                  cantNum = 3;
                  formatofinal ='s';
              }
              else if (digits_count(n) === 4) {
                  cantNum = 2;
                  formatofinal ='s';
              }
              else if (digits_count(n) === 5) {
                  cantNum = 3;
                  formatofinal ='s';
              }
              else if (digits_count(n) === 6) {
                  cantNum = 3;
                  formatofinal ='s';
              }
              else if (digits_count(n) === 7) {
                  cantNum = 2;
                  formatofinal ='s';
              }
              else if (digits_count(n) === 8) {
                  cantNum = 3;
                  formatofinal ='s';
              }
              else if (digits_count(n) === 9) {
                  cantNum = 3;
                  formatofinal ='s';
              }
              else {
                  cantNum = 2;
                  formatofinal ='s';
              };
          }

          function formatear(n) {
            // Process cantNum and formatofinal here ... function call
            processCantNumAndFormatOfinal(n);
            const formato = simbol + format(",."+ cantNum +formatofinal)(n)
                .replace('.', ',')
                .replace('G', 'B');
                return formato;
          };

          return function(n)
          {
            return formatear(n);
          }
        }
    })()
}

Я также пробовал использовать стрелочную функцию, но данные обнуляются.

.merge(numeros)
     .transition().duration(this.tiempo)
     .tween(this.label, d => {
         var i = interpolate(1, d.population);
         if (d.population != 0)
         return (t) => { //..}

EDITED:

Теперь у меня заметил 2 вещи:

  1. this.label не распознается внутри функции (t). Когда я преобразовываю это:
(this.label === 'labelg1')

в это:

(this.label != 'labelg1')

условие распознается, но теперь я получил сообщение об ошибке:

Uncaught TypeError: _this3.formatCurrency is not a function

EDITED 2:

Я изменил подход для formatCurrency, это новая структура:

import { format } from 'd3';

export default {
    methods: {
        formatCurrency(n) {
           let count = digitsCount(n)
           let numeros = processCantNumAndFormatOfinal(count)[0]
           let formatoF = processCantNumAndFormatOfinal(count)[1]
           let final = formatear(numeros, formatoF, n)
           console.log(final)
           return final
       }
    }
}

function digitsCount(n) {
            let count = 0;
            if (n >= 1) ++count;

            while (n / 10 >= 1) {
              n /= 10;
              ++count;
            }
            return count;
        }

function processCantNumAndFormatOfinal(n) {
            let cantNum;
            let formatofinal;
            if (n === 0) {
              cantNum = 0;
              formatofinal ='r';
            }
            else if (n === 1) {
              cantNum = 1;
              formatofinal ='s';
            }
            else if (n === 2) {
              cantNum = 2;
              formatofinal ='s';
            }
            else if (n === 3) {
              cantNum = 3;
              formatofinal ='s';
            }
            else if (n === 4) {
              cantNum = 2;
              formatofinal ='s';
            }
            else if (n === 5) {
              cantNum = 3;
              formatofinal ='s';
            }
            else if (n === 6) {
              cantNum = 3;
              formatofinal ='s';
            }
            else if (n === 7) {
              cantNum = 2;
              formatofinal ='s';
            }
            else if (n === 8) {
              cantNum = 3;
              formatofinal ='s';
            }
            else if (n === 9) {
              cantNum = 3;
              formatofinal ='s';
            }
            else {
              cantNum = 2;
              formatofinal ='s';
            }
            return [cantNum,formatofinal]
        }

function formatear(cantNum, formatofinal, n) {

            let formato = format(",."+ cantNum + formatofinal)(n)

            return formato;
         }

И для компонента:

<template>

</template>

<script>

import formatCurrency from '../mixins/formatCurrency';
import formatTime from '../mixins/formatTime';

//...
async mounted() {
        let datos = await csv('/datasets/data.csv')
        this.dataset = Object.freeze(datos)
        this.dataNumero
        this.filtrarData
        this.graph()
        this.formatearData
    },
//...
computed: {
//...
        dataNumero() {
            this.dataset.forEach( function(d) { return d.population = +d.population})
        },
        filtrarData() {
            this.dataFiltrada = this.dataset.filter(function(d) { return d.country !== 'Total'})
        },
        formatearData() {
            this.dataFiltrada.forEach( function(d) { return d.population = this.formatCurrency(d.population) })
        },

methods: {
        graph() {
        //..
        const numeros = g.selectAll(this.label).data(this.dataFiltrada)
                numeros
                    .enter().append("text")
                        .attr("class", this.label)
                        /* esto les da posición a las etiquetas en x e y */
                        .attr('x', this.xEtiqueta)
                        .attr('y', d => { return -yScale(d.country); })
                        .attr('dy', this.yEtiqueta)
                        .text(0)

                    /* esto agrega las transiciones */
                    .merge(numeros)
                        .transition().duration(this.tiempo)
                        .tween(this.label, function(d) {
                            var i = interpolate(1, d.population);
                            if (d.population != 0)
                            return function(t) {
                                select(this).text(Math.round(i(t)))
                            };
                        })
//..
    mixins: [
    formatCurrency,
    formatTime
    ],


с функция стрелки в formatearData() {this.dataFiltrada.forEach(d => //.. консоль показывает результаты нормально, но диаграмма показывает значения NaN во всех числах, превышающих 3 цифры (?????), когда я изменил formatearData(), удалив стрелочную функцию formatearData() {this.dataFiltrada.forEach(function(d) { d.population = //.., ошибка : Error in mounted hook (Promise/async): "TypeError: Cannot read property 'formatCurrency' of undefined" Изображение ниже для справки. введите описание изображения здесь

EDITED 3:

Хорошо, функция, которая не работает, - это формат d3, проблема в том, что я попытался отформатировать номер текстовой метки гистограммы d3 с помощью специальных формат, но когда это происходит, числа преобразуются в строки и отображает значение NaN, поэтому возникает соответствующий вопрос: есть ли способ отформатировать номера столбцов D3-диаграммы в vue во время перехода между анимацией или другим методом? потому что этот код работает идеально подходит с простым javascript и webpack, но с vue совсем другая история.

1 Ответ

0 голосов
/ 05 августа 2020

избегайте использования arrow functions ключевого слова this. Используйте его как:

select(this).text(function(d){
    return (this.label === 'labelg1')                                            
         ? this.formatCurrency(i(t))                   
          : this.formatTime(i(t))                                   
} 

Для получения дополнительных сведений Прочтите this.

...