The error message "TypeError: Cannot access property 'chart' of undefined" is showing up when using Vue Highcharts

Trying to incorporate a Highcharts chart into Vue.js using Highcharts for Vue has been proving challenging. The browser console keeps throwing an error related to the watcher I set up and the methods I implemented (refer to the code snippet below). Similar errors are also occurring with other Vue methods, as depicted in the screenshot provided.

The watcher is responsible for triggering the dataSource() method, which reads the list data and calculates the necessary chart information. The "base" constant holds the core category and data extraction logic. Meanwhile, the setup() method configures and displays the chart on the interface, but it will only execute once the data is fully loaded.

How can these errors be resolved?

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script>
import { mapState } from "vuex";
import _ from "lodash";
import { Highcharts } from "highcharts";

export default {
  computed: mapState({
    list: state => state.list
  }),

  //Watcher for every modification of the list, triggers the dataSource() method
  watch: {
    list() {
      this.dataSource();
    }
  },
  methods: {
    
    dataSource() {
      const countries = this.list.map(item => item.country);

      
      const base = _(countries)
        .countBy()
        .map((value, key) => ({ key, value }))
        .orderBy(["value"], ["desc"])
        .value();

      const categories = base.map(item => item.key);
      const values = base.map(item => item.value);

      this.setup({ categories, values });
    },

    
    setup(obj) {
      const { categories, values } = obj;

      Highcharts.chart("container-for-countries", {
        chart: {
          type: "column"
        },
        title: {
          text: "Monthly Average Rainfall"
        },
        subtitle: {
          text: "Source: WorldClimate.com"
        },
        xAxis: {
          categories: categories,
          crosshair: true
        },
        yAxis: {
          min: 0,
          title: {
            text: "Rainfall (mm)"
          }
        },
        series: [
          {
            name: "Quantidade",
            data: values
          }
        ]
      });
    }
  }
};
</script>

https://i.sstatic.net/IOEn4.jpg

Answer №1

Check out the Highcharts package on NPM here!

According to the documentation, you can easily load Highcharts as an ES6 module.

import Highcharts from 'highcharts';

You're utilizing a named import for this module.

Just a side note - why opt to load Vue.js from a CDN while importing other libraries?

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

Error: Attempting to access property of undefined variable

I have searched for similar titles related to my issue, but I still haven't found a solution. The error I am encountering when clicking on agent_dashboard on the side panel is as follows: txtDisplayName = <div style="border:1px solid #990000;paddi ...

Issue with accessing VueJS Global Mixin readonly variable in component method

Trying to integrate vuejs as a frontend framework with WP restapi, I faced the challenge of needing the wordpress generated api url accessible to all vue components. Here is my approach: Vue.mixin({ data: function () { return { get apiUrl () { ...

Deleting a record in MongoDB based on a specific value present in a column

I am in search of more information about delete triggers in MongoDB. Source: Query on MongoDB Delete Triggers I am interested in converting DELETE operations to UPDATE + AUTOMATIC DELETE. To achieve this, I plan to introduce a new field called "flag" ...

Tips for displaying AngularJs content in the View Source

I utilized AngularJs to incorporate a large amount of content. Unfortunately, the content does not appear in the view source. Is there a way for the view page to display content in the view source using AngularJs? I am unable to see the contents I added ...

Dynamically obtaining the screen width in JSP using a variable

Could someone provide assistance on how to resize an image using an img src="blah.jpg?width=x" so that my page can be displayed at various sizes? I just need x (width) as a JSP variable. Update 2021: It's been 9 years since this question wa ...

Encountering an issue with my node configuration while working on a Discord bot

Attempting to develop my own Discord Bot has presented me with a challenging error that I am struggling to resolve: internal/modules/cjs/loader.js:968 throw err; ^ Error: Cannot find module './commands/${file}' Require stack: - C:\Users&bso ...

Modify code on click using JavaScript

Here is some code I found for a custom style switcher: I am thinking about integrating it into my bootstrap dropdown button. The current code for the style switcher is as follows: <form id="switchform"> <input type="radio" name="choice" value= ...

How can I convert an object array back into an iterated collection after using the find() method in MongoDB?

Currently, I am working on developing an application using AngularJS, NodeJS, and MongoDB. My goal is to load Products classified by ProductCategoryCode sent from AngularJS to NodeJS. The process involves finding Products based on ProductCategoryCode, iter ...

Creating a personalized message for a failed "Get" request using the HTTPS native module in combination with

Currently, I have implemented an Express application that includes an HTTP GET request to an external API. It functions properly when there are no errors; however, I am looking to customize the response sent to the client-side in case of failures: const ht ...

Retrieve a single value from a JavaScript array

There must be something simple I am missing here, as all the search results I found relate to looping over arrays, which is not what I want. My ajax call returns a response in the form of a straightforward array. When I use console.log(response); in the s ...

I am exploring directories on my server but encountered a restriction while using $.ajax

I am currently working on designing a basic webpage using p5.js, where I have implemented a script to search for images within folders and display them all on a single page. To facilitate this process, I am utilizing the $.ajax({}); function to check ...

Retrieve the username after making a call to this.$auth.fetchUser() in Nuxt

Hey there, I've been trying to retrieve the username after using the fetchUser method but it keeps showing as undefined. This is how I have been attempting: async loginUser() { this.$auth.setUserToken(`${this.token}`); this.$auth.setS ...

Utilize JavaScript to activate a new browser tab and monitor its status for closure

When I attempt to open a new tab using JavaScript and track when it is closed, none of the events are being triggered. All the examples I found reference the onbeforeunload event for the current window, not for other window objects. window.addEventListe ...

How can you resize an HTML table by dynamically adding or removing rows and columns?

Is there a way to dynamically add or remove rows and columns from an HTML table, also known as resizing it? The table should have a rectangular shape as it will later represent a 2D array value. Since the table will be refreshed frequently and may become ...

Long X-axis labels on D3 chart causing overlap issue

I am facing an issue with my D3 Bar chart where the X-Axis labels are overlapping. Here is the code snippet that I have: // implementing word wrapping for x axis svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height ...

The Ajax submit button is only operational for a single use

Check out my basic HTML form and JS setup: <body> <form> <label for="usrtext">Type your text here:</label> <br /> <textarea name="usrtext" id="usrtext" rows="25" cols="100"></textarea> ...

Using Jquery to access the grandparent element

When I have code similar to what is shown below, an element contains within 3 layers: <span class="dropdown test1"> <span class="test2" type="button" data-toggle="dropdown">hello</span> <ul class="dropdown-menu test3" style="m ...

Displaying the revised v-model value in the input field is not possible at the

Here is a code snippet that I am working with: const BasicInput = { template: '<input v-model="content" @input="handleInput" />', prop: ["value"], data() { return { content: this.value }; }, methods: { handleI ...

Reorganizing asynchronous code into a nested synchronous structure in Meteor/React

Recently, I've been experimenting with running data fetching code in a container component and passing it to the display component in order to streamline my use of hooks and reduce load time. I've tested both await/sync and Meteor's wrapAsyn ...

Creating buffer geometries for spheres using Three.js

Currently, I am working on a three.js project that involves displaying numerous spherical objects. To achieve this quickly, I decided to utilize buffergeometry. Upon researching, I came across a helpful post here, where I learned that I could transform nor ...