"VueJs and ChartJs work together to create single file components, but the computed property is only rendered in Vue Dev Tools when the component is

Currently, I am working on a single file component that utilizes Chart.Js to display a basic visualization of some hardcoded data. The Chart.Js library is being called from a CDN placed in the head section of my index.html file.

The project is based on the official Webpack template.

Strangely, the chart does not render unless I interact with the component within the Vue Dev Tools extension.

I have attempted switching between computed and created/mounted methods, but it has not resolved the issue.

Provided below is my code. Any assistance in resolving this rendering problem would be greatly appreciated.

<template lang="html">
  <div>
    <div class="row">
      <div class="col-sm-12 col-md-4">
        <canvas id="carbChart"></canvas>
      </div>
    </div>
  </div>
</template>

<script>

export default {
  data() {
    return {
      calories: 3000,
      childSex: 'male',
      childAge: 'eighteen'
    }
  },
  computed: {
    nutrientCharts: function() {
      let calories = this.calories;

      let carbCtx = document.getElementById('carbChart').getContext('2d');

      let carbChart = new Chart(carbCtx, {
        type: 'doughnut',
        data: {
          labels: ['Low', 'Good', 'Too Much'],
          datasets: [{
            label: 'carbs',
            data: [calories * .45, calories * .65, calories * 1],
            backgroundColor: ['orange', 'blue', 'red']
          }]
        }
      });
    }
  }
}
</script>

Answer №1

The method has been defined within a computed property but has not been utilized.

If your main goal is to make it work, you can load the chart when the component is mounted:

mounted() {
  this.displayNutrientCharts();
},
methods: {
  displayNutrientCharts: function () {
    // add your code here
  }
}

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

Using regex, match any word along with the preserved white space and consider parentheses as a single word

I need help with creating a regex pattern to split a string of words in a specific way. The current pattern I've been using is (?!\(.*)\s(?![^(]*?\)), but it's not giving me the desired outcome. It's close, but not quite the ...

The parameter provided should be in the form of a 12-byte string

Hey there, I am facing an issue while trying to delete an entry in my database. Despite attempting JSON.parse on the req.body and rearranging the routes in my routes file, I still can't seem to get it to work. Here is my controller: async function re ...

Using app.js in a blade file can cause jQuery functions and libraries to malfunction

In my Laravel application, I am facing an issue with my vue.js component of Pusher notification system and the installation of tinymce for blog posts. Adding js/app.js in my main layout blade file causes my tinymce and other jQuery functions to stop workin ...

Challenges with Page Loading in Selenium

Inquiry: When a URL is accessed in a web browser, the page begins to load. A loading symbol appears at the top, and once it stops, our selenium script continues with the next steps. However, there are instances where the page takes longer to load all its ...

Restful Spinner

app.config(function(RestangularProvider) { RestangularProvider.addRequestInterceptor(function(element) { console.log("Request initiated"); return element; }); RestangularProvider.addResponseInterceptor(function(data) { ...

Using jQuery to efficiently handle dynamically added elements by combining the ".on" and ".each" methods

I am currently in the process of dynamically inserting new elements into my page, and these elements have a specific structure that is represented as follows: <div id="cars"> <input type="text" name="car_added[]" class="car" /> <inp ...

What is the process for retrieving data through a server-side API request?

I have been working on setting up my API URL in my Node.js backend application. I initially passed the entire URL in my frontend AJAX call, but now I want to transition to a server-side API call to avoid exposing the URL. Since I am not very experienced wi ...

The data is not being successfully transmitted to the controller method through the AJAX call

In my JavaScript file, I have the following code: $(document).ready(function () { $('#add-be-submit').click(function (event) { event.preventDefault(); $.ajax({ type: 'POST', url: '/snapdragon/blog/new&apos ...

How can I redirect to a different page with a keypress event in Next.js?

I am looking to implement a redirection function in nextjs when users press a key. There is a search input field where users can type and then hit the enter key to navigate to another page. Here's what I have attempted: const handleKeyPress = (e) = ...

The steps to implement an onchange function for displaying image previews in a profile image tag

Within my code, there is a profile image tag along with an input tag for updating the image. I aim to implement a functionality that allows me to select a new image and automatically update the profile picture when it changes <div class="col-sm-6"> ...

Ways to create a shorter upper line compared to the lower line (inside a div)

I'm dealing with an unordered list that has 3 list items, each represented by a green box containing an image and 3 divs (title, location, price). My main focus is on the title div of each box. If the title is long enough to span 2 lines, I need the ...

The initial execution of the getDocs function may encounter some difficulties

Whenever a user connects from localhost:3000/ (which automatically redirects to /profile), I try to fetch all documents from Firebase. However, it does not work on the first attempt. Strangely, upon refreshing the page, it successfully retrieves the docume ...

Tips for extracting value from a chosen input field without relying on its unique identifier

I am working on a simple code to help guess notes by ear. The concept involves tabs with empty input fields where numbers need to be entered based on a specific melody for the guitar fretboard. One button reveals the first note, while another button checks ...

User missing in the transition from POST to GET

My journey with Node has just begun, and I decided to delve into the Rocket Rides demo available on GitHub. While exploring the pilot sign-up feature on the web app, I encountered a roadblock when trying to implement a similar functionality for passenger s ...

301 redirection will be implemented on the upcoming static export

Working on a Next.js project, I utilized static export for better performance and SEO. Yet, I've come across an issue with URL changes. I'm looking to incorporate a 301 redirect to ensure search engines and users are directed to the correct pages ...

"Resolving the problem of populating an empty array with JSON

My JSON structure at the top level is set up like this: { "video": [], "messages": [], "notifications": [] } In the database output stored in a variable called "result," I have data that I want to add to the "vide ...

Consistently encountering incorrect values during onClick events

I am using a Table to display certain values const [selected, setSelected] = React.useState<readonly number[]>([]); const isSelected = (id: number) => selected.indexOf(id) !== -1; return ( <TableContainer> <Table sx={{ width ...

Unable to display values in Fusion Charts zoomline chart using the showValues chart property

I'm struggling to figure out how to display the data plot values with showValues: '1' in a zoomline chart using Fusion Charts. You can see and test it on this fiddle: http://jsfiddle.net/60oeahc1/4/ Is there a way to make this feature work ...

Display Image Automatically Upon Page Opening

Currently, I have an HTML file that includes the following code: <img src="(Image from file)" alt="Raised Image" class="img-raised rounded img-fluid"> I am attempting to retrieve the image from a file when the webpage loads using the server.js file ...

Set the Vue instance data to a variable that does not react to changes

One issue I'm encountering is with a form that utilizes a modal to populate an array within the form. Each time the modal is submitted, a Vue object is pushed into an array on the main form. However, the problem arises when editing one item in the arr ...