Transferring information from an external JavaScript file to a Vue component

I am currently facing an issue with passing data from an external file called data.js to the component for its usage. The error I'm encountering states that the data is not defined.

Below is the content of my data.js file:

const data = [
  {
    chartOptions: {
      chart: {
        type: "boxplot",
        inverted: true,
        height: 200
      },
      credits: {
        enabled: false
      },
      legend: {
        enabled: false
      },
      series: [
        {
          name: "Observations",
          data: [[100, 221, 250, 300, 411]]
        },
        {
          name: "Company name",
          color: "yellow",
          type: "scatter",
          data: [[0, 200]],
          marker: {
            fillColor: "yellow",
            lineWidth: 1,
            lineColor: "yellow"
          }
        }
      ]
    }
  },
  {
    chartOptions2: {
      chart: {
        type: "boxplot",
        inverted: true,
        height: 200
      },
      credits: {
        enabled: false
      },
      legend: {
        enabled: false
      },
      series: [
        {
          name: "Observations",
          data: [[120, 231, 222, 320, 321]]
        },
        {
          name: "Company name 2",
          color: "yellow",
          type: "scatter",
          data: [[0, 210]],
          marker: {
            fillColor: "yellow",
            lineWidth: 1,
            lineColor: "yellow"
          }
        }
      ]
    }
  }
];

export default data;

The problematic component where I need to access the data is shown below:

<template>
  <div>
    <highcharts class="hc" :options="chartOptions" ref="chart"></highcharts>
    <highcharts class="hc" :options="chartOptions2" ref="chart"></highcharts>
  </div>
</template>

<script>
import data from "./data.js";

export default {
  data () {
    return {
      data
    }
  }
};
</script>

To experiment with this setup, you can also visit this codesandbox link.

Answer №1

Transform your data.js into an object format instead of an array:

const data = {
    chartOptions: {
      chart: {
        type: "boxplot",
        inverted: true,
        height: 200
      },
      credits: {
        enabled: false
      },
      legend: {
        enabled: false
      },
      series: [
        {
          name: "Observations",
          data: [[100, 221, 250, 300, 411]]
        },
        {
          name: "Company name",
          color: "yellow",
          type: "scatter",
          data: [[0, 200]],
          marker: {
            fillColor: "yellow",
            lineWidth: 1,
            lineColor: "yellow"
          }
        }
      ]
    },
    chartOptions2: {
      chart: {
        type: "boxplot",
        inverted: true,
        height: 200
      },
      credits: {
        enabled: false
      },
      legend: {
        enabled: false
      },
      series: [
        {
          name: "Observations",
          data: [[120, 231, 222, 320, 321]]
        },
        {
          name: "Company name 2",
          color: "yellow",
          type: "scatter",
          data: [[0, 210]],
          marker: {
            fillColor: "yellow",
            lineWidth: 1,
            lineColor: "yellow"
          }
        }
      ]
    }
  }
export default data;

Next step is to use the object in your component:

import data from "./data.js";

export default {
  data () {
    return {
      chartOptions: data.chartOptions,
      chartOptions2: data.chartOptions2,
    }
  }
};

Answer №2

To correctly define the key/value pair, you need to do the following :

 data() {
    return {
     charts:data
    };
  },

In your template, make sure to access the items in the charts array like this:

<div>
    <highcharts class="hc" :options="charts[0].chartOptions" ref="chart"></highcharts>
    <highcharts class="hc" :options="charts[1].chartOptions2" ref="chart2"></highcharts>
  </div>

https://codesandbox.io/s/highcharts-vue-demo-5mt7l?fontsize=14&hidenavigation=1&theme=dark

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

Utilizing Google Tag Manager for Efficiently Managing Multiple Schema Product Reviews with JSON-LD and Variables

Currently, I am facing a challenge while using Google Tag Manager to incorporate Schema JSON-LD Product reviews on certain pages. Despite my efforts, I am unable to locate any relevant resources to resolve this issue. The main problem lies in informing GT ...

What is the reason behind the decision for Google Chart API to display a legend only for pie charts

I have encountered an issue while attempting to display a pie chart on an ASP.NET webpage using the provided URL: . Despite passing valid values in the URL parameters, only the legend of the chart is displayed and not the chart itself. Can anyone provide i ...

How to Build a Custom Toolbar with Left and Right Aligned Elements using React.js and Material UI

Struggling with updating the toolbar on my website. Wanting the site name and logo on the left side, while login/sign-up buttons fixed to the right. Logo and title are in place, but can't get buttons to stay on right margin. Here's the code: func ...

Automatically trigger the Submit button click with this selector

I'm having trouble automating the clicking of a 'Submit' button that only becomes clickable after a specific action is taken. In this case, the user needs to click the TOS checkbox before the button can be clicked. I've been unable to f ...

Creating a responsive class getter with Vue.js 3 using the Composition API: a guide

How can I set up a class instance property to reactively display an error message when authentication fails? UserModel.ts export class User { private error: string; set errorMessage(errorMessage: string) { this.error = errorMessage; } get err ...

Struggling with a $ref that points to a Proxy object within vue-router

After transitioning from using VueJS in browser mode to a VueJS SPA with vue-router, I am facing issues with my code as $refs is no longer functioning correctly. Previously, I was able to interact with my Google Charts by referencing the graph (this.$refs ...

Creating dynamic fields for an ExtJS chart

Can chart axes be customized using setFields? I looked through the documentation for a method called setFields, but couldn't find one. While I was able to use setTitle on an axes, setting the field proved to be more challenging. I have a variable ca ...

Using JavaScript to save a file with a data URL in Internet Explorer

Need help with file conversion on different browsers. I developed an app that converts files, and everything was working perfectly in Chrome. However, when it comes to IE (10/11/Edge), I'm facing some challenges: 1) The HTML5 download attribute does ...

The method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not provide any output

After running all JavaScript, I need to retrieve the HTML content. However, I am facing an issue using WebKit.NET where the method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not return anything, even with a simple alert(). When I try passi ...

Having trouble with Vue.js? My simple program isn't displaying any output

Just diving into the world of Vue.js, I've been learning it recently. However, this basic code snippet isn't displaying any output. Can someone please provide assistance? <html> <head> <title>Vue Js | Learning Journey </titl ...

Enhanced Search and Replace Techniques in HTML using jQuery and JavaScript

Although I have some experience with jQuery and Javascript, I am by no means an expert. I have been struggling to find a way to achieve my goal using minimal resources. Maybe you can assist me: This is what I am trying to accomplish: I would like to use ...

Error TS2307: Module 'calculator' could not be located

Running a Sharepoint Framework project in Visual Studio Code: This is the project structure: https://i.stack.imgur.com/GAlsX.png The files are organized as follows: ComplexCalculator.ts export class ComplexCalculator { public sqr(v1: number): number ...

Passing multiple functions to child components in ReactJS as a single prop

I am utilizing the technique of passing multiple functions as individual props from the parent component to its child components. Everything is working correctly without any errors or problems, but I'm interested in exploring if there is a more effici ...

When tab switching occurs, the alert box fails to be processed by the browser

When using the alert(message) function, it will display an alert box with a message and an OK button. It will also pause the execution of any code that follows until the OK button is clicked. However, I have noticed a peculiar situation where switching tab ...

Having issues with React-router v4's this.props.history.push() not functioning as expected

I'm attempting to programmatically redirect using the this.props.history.push(..) method, but for some reason it's not working. Here is the routing setup: import { BrowserRouter as Router, Route } from 'react-router-dom'; <Route ...

Executing multiple AJAX requests with promises in Angular based on an array of values

I have been working on implementing multiple ajax calls in sequence using Angular. Interestingly, everything seems to be working fine when I use $.ajax, but when I switch to using $http for server requests in Angular, things start to go awry. Both methods ...

ajaxStart - Display change inconsistency

These are some helpful comments to shorten and improve the readability of the code In my current project, I am using Javascript (Ajax) along with PHP (Laravel). I encountered an issue where I have set up two listeners in my ajax function. One listener is ...

Having trouble with Lerna bootstrap? You might be running into the dreaded npm error code E401

Every time I run Lerna bootstrap on Jenkins, it fails with an error, but it works fine on my local machine. npm ERR! code E401 npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager" Package.json in the main folder ...

Retrieve DirectionsResult data from a Google Maps URL

Currently, I am developing an updated tool that can transform Google Maps directions into GPX files. The initial version of this tool is performing quite well: it utilizes the Google Maps Javascript API (v3) to showcase a map on the website, allowing users ...

Refresh the Content of a Page Using AJAX by Forcing a Full Reload

I have a webpage that automatically updates a section using jQuery AJAX every 10 seconds. Whenever I modify the CSS or JavaScript of that page, I would like to include a script in the content fetched via AJAX to trigger a full page reload. The page is ac ...