Utilizing props as option data for Echarts within a Vue 3 component - how can I make this possible?

I've been facing a challenge while working with Echarts to create a line chart. I have created a LineChart.vue component in which I expect to receive array props from its parent component to use as data options for Echarts.

However, the array props, which act as proxies for the arrays, don't seem to function correctly. Although the console shows that they are targeting the right object, Echarts does not recognize these proxies, resulting in no data being displayed on the chart.

What's more puzzling is that I discovered a workaround by accident - if I leave my terminal open, make some insignificant changes to the code (such as commenting and uncommenting the same lines), and save it (triggering a re-render of the component), the props magically start working and the line chart appears! But upon page refresh, the data disappears again.

Below is the code snippet:

<template>
  <div id="chart"></div>
</template>

<script>
let chart;
export default {
  data() {
    return {
      option: {
        name: "demo",
        xAxis: {
          type: "category",
          data: [],
        },
        yAxis: {
          // type: "value",
        },
        series: [
          {
            data: [],
            type: "line",
          },
        ],
      },
    };
  },
  props: {
    xAxisData: Array,
    seriesData: Array,
  },
  methods: {
    initChart() {
      chart = this.$echarts.init(document.getElementById("chart"));
      
      // These four lines were the ones I manipulated to achieve the 'weird' result
      this.option.xAxis.data = this.xAxisData;
      this.option.series[0].data = this.seriesData;
      console.log(this.option.xAxis.data);
      console.log(this.option.series[0].data);

      chart.setOption(this.option);
    },
  },
  mounted() {
    this.initChart();
  },
  watch: {
    xAxisData: {
      handler: function (newData) {
        this.option.xAxis.data = newData;
      },
      deep: true,
    },
    seriesData: {
      handler: function (newData) {
        this.option.series[0].data = newData;
      },
      deep: true,
    },
  },
};
</script>

<style scoped>
#chart {
  height: 250px;
  width: 400px;
}
</style>

Here iswhat the proxy looks like before and after minor code changes. I also attempted using Object.assign() to convert the proxy xAxisData into an object, but it appeared empty! Could this be related to the component lifecycle? I'm unsure about when and where I can obtain a functional proxy. Any insights on what might be causing this issue?

For reference, here are the values of the props shown in the console (console) and in Vue devtools (Vue devtools).

Answer №1

After some troubleshooting, I finally cracked the code. It turns out that the information provided earlier was not sufficient, and I ended up making a rookie mistake.

The issue stemmed from an asynchronous request in my Vue component. The data for my Echarts props was being fetched through an Axios request, resulting in my child-component (the linechart) rendering before receiving the necessary data. This caused the arrays' proxies to show no data initially, even though their targets were displayed correctly. By the time the child-component obtained the correct data, the Echart had already been rendered with outdated and empty options data. This lack of reactivity in Echarts prompted me to manually update the options by watching the props like so:

watch :{
  xAxisData: {
      handler: function (newData) {
        this.option.xAxis.data = newData;
        this.chart.clear();
        this.chart.setOption(this.option);
      },
      deep: true,
    },
}

And voilà, it worked like a charm!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with the "Corrupted @import" error during grunt build?

As I embark on my journey to create my very first Angular application, I have encountered a roadblock. Using Yeoman and angular-generator, everything seemed to be running smoothly with "grunt serve." However, when I attempted to execute "grunt build," the ...

Duplicate an $sce generated entity and adjust its content

I am facing a situation where I have a variable structured in the following way: tableData1[$scope.tableHeadingsConstant[0]] = $sce.trustAsHtml('<div class="header12" id="runTitle0" style="cursor: pointer;">' + counter ...

retrieving user information from the auth.users table in Supabase

I have set up a recipes table in supabase, with a user_id foreign key that corresponds to the auth.user.id in the built-in users table. Now, I am attempting to retrieve all the recipes along with the user's date (user_id in recipe table): export async ...

Whenever the click event is triggered, Ajax is making numerous duplicate calls

Each time I click to fetch my content using an AJAX call, the calls end up duplicating themselves. I've tried various on-click events I came across on Stackoverflow threads, but unfortunately none of them seem to be solving the issue. $(document).rea ...

Find the difference in weeks between two dates using MongoDB aggregate

My current dilemma involves extracting student data for each week within an academic year based on a start date and end date. To achieve this, I have devised an array that contains the start and end dates for every week. The process involves iterating thro ...

Refresh the vue-chart component in a nuxt.js application

I'm currently working on a nuxt project and I need to incorporate some charts into it. I'm using vue-chartjs as a plugin for this purpose. However, the issue I'm facing is that the chart data is fetched after the chart has already been drawn ...

Passing an array through ajax from PHP to JavaScript using a properly formatted JSON structure

I began with an array generated by PHP and retrieved via ajax, which had the following structure: Array ( [0] => {id:"12",from:"09:00:00",to:"15:00:00"} [1] => {id:"13",from:"08:00:00",to:"10:00:00"} [2] => {id:"12",from:"15:00:00",to ...

DirectUpload is failing to trigger directUploadWillStoreFileWithXHR for file storage

I have implemented Rails ActiveStorage on an ECS class import { DirectUpload } from "@rails/activestorage"; function createDirectUpload(file, source, controller) { return new DirectUpload(file, source.url, source.token, source.attachmentName, ...

What is the method for including the value of a missing object once it has been compared to another array

My task involves dealing with an array of months (var months). I want to filter out the months that are missing in another array of objects (var array1) and add a property Avg with a value of 0 for those missing months. var months = ["Jan", " ...

Conceal the form node's visibility upon initial inspection

My goal is to understand how the "add a comment" feature on Stack Overflow works by examining the code in three sections: footnote-list, footnote-form, and add-form-link. footnote-list footnote-form add-form-link <div class="col-md-12 footnotes"> ...

Error: HTMLButtonElement on notes-taking website unable to read property 'push' of null

I'm encountering an issue with this code that is resulting in an error message: Uncaught TypeError: Cannot read property 'push' of null at HTMLButtonElement. (app.js:15) console.log("Welcome to Notes Taking Website"); // To sto ...

Unable to invoke function within class using 'this'

I've been working on a class named Scheduler that runs a cron job using the cron module. I've defined a function to calculate the difference in days between two dates, and it works fine when called outside of the cron job iteration. However, if I ...

Is it possible to return a promise within the .then function in AngularJS?

I have a unique service called "usersService". I want to create a special method that interacts with another custom service I built. This other service has two handy methods: getUser() and getCurrentUser(). The getCurrentUser() method relies on the injecte ...

An alternative approach to dynamically adding a class to a DOM element using AngularJS that reduces repetition

Creating an AngularJS application with materializecss for the UI involves adding the focused class to all form elements for specific behavior. To streamline this process, you can use the ng-class directive on the parent container and define a variable tha ...

How can I use Chart.js to assign a unique color to each x-axis label?

I'm currently using Chart Js to create a chart and I want each label to have a different color instead of all labels having the same color. Is there a way to achieve this using the ticks callback function? scales: { xAxes: [{ ...

What is the process for extracting a nested document from an array of documents in mongodb?

I am currently facing a challenge in my project where I need to remove a nested objects array within a document. The specific scenario involves searching for the days on which an event will be held, based on its event ID. const { eventid, typesOfTicketId ...

What could be causing anime.js to malfunction when clicked in Vue.js?

After implementing the mounted() function, the animation now successfully plays when the page is updated. However, there seems to be an issue as the animation does not trigger when clicked. Even though console.log registers a click event, the animation fa ...

Hold tight for the response from the AngularJS factory request

In my Rails application, I am incorporating Angular. The code snippet below shows an API request being made and the code in the .run function being executed. Sometimes, the API response is still pending when the code is executed. This leads to issues with ...

Show a webpage depending on specific JavaScript criteria

I have a condition in my JavaScript code that determines whether or not a user should be granted access to a specific page. However, I don't want users to be able to directly access this page even if they know the URL. This page contains both HTML and ...

Tips for calculating the cumulative values from various documents within a collection and transferring the total sum to a separate document in another collection

In my current project, I am working with recipes and ingredients. Each of these entities has its own model and controller. A recipe can have multiple ingredients and the calorie amount of each ingredient is stored in the "calories" field. The main challeng ...