Is the VueJs and ChartJs combination causing the chart to be width-responsive, but not height-responsive?

I've exhausted all options, but I can't seem to make the height of my chart respond effectively.

The width is behaving as expected, adjusting responsively, but the height stubbornly remains fixed at 400px.

Within my primary Vue application, I invoke my component (passing in the chart data):

<ProjectedCumulativeSavings :datacollection="projectData.projectedCumulativeSavings" />

The code for the ProjectedCumulativeSavings.vue component is as follows:

<template>
    <div class="chart-container" >
        <bar-chart
            :chart-data="datacollection"
            :options="options"
            chart-id="projectedCumulativeSavings"
        />
    </div>
</template>

<script>
import BarChart from '../mixins/BarChart.js'

export default {
    components: {
        BarChart
    },
    props: {
        datacollection: ''
    },
    data() {
        return {
            options: {
                maintainAspectRatio: false,
                responsive: true,
                title: {
                    display: true,
                    text: 'Projected Cumulative Savings',
                    fontSize: 18
                },
                legend: {
                    display: false
                },
                scales: {
                    yAxes: [{
                        ticks: {
                            // Include a dollar sign in the ticks
                            callback: function (value, index, values) {
                                return 'R' + value.toLocaleString('en')
                            }
                        }
                    }]
                }
            }
        }
    },
    created() {
    },
    computed: {
    }
}
</script>

<style >
.chart-container {
    min-width: 375px;
    max-width: 1024px;
    /* margin: 30px; */
    position: relative;
    width: 100%;
    height: 40vw;
}
</style>

The code for BarChart.js is as follows:

import { Bar, mixins } from 'vue-chartjs'
const { reactiveProp } = mixins

export default {
    extends: Bar,
    mixins: [reactiveProp],
    props: ['options'],
    mounted() {
        // this.chartData is created in the mixin.
        // If you want to pass options please create a local options object

        this.renderChart(this.chartData, this.options)
    },
    watch: {
        chartData() {
            this.$data._chart.update()
        }
    }
}

Answer №1

I encountered the same issue and stumbled upon a solution.

https://www.chartjs.org/docs/latest/general/responsive.html#important-note

Give this a try

    <bar-chart
        :chart-data="datacollection"
        :options="options"
        :styles="myStyles"  <-- include this
        chart-id="projectedCumulativeSavings"
    />

Also

    computed: {
        myStyles() {
          return {
            height: '20vh',   <-- this ensures your chart is responsive
            position: 'relative',
          };
    },

Answer №2

The solution that proved effective for me was specifically defining the height and width of the component like this:

<BarChart
   :chart-data="chart2Data"
   :options="chart2Options"
   :key="chart2Trigger"
   :height="2"
   :width="4"
 />

Answer №3

When working with Vue3 and vue-chartjs, I encountered a similar issue. The way I resolved it was by setting the options to { response : false }, and then defining the style object with computed properties.

Here's how I did it, by defining the computed style first:

const chartStyle = computed(() => {
  return {
    height: '20vh',
    width: '100%',
    position: 'relative',
  }
})

After that, I added it to the <Bar> component as a style prop:

<Bar
  :style="chartStyle"
/>

I hope this solution helps you as well.

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

JavaScript Array Multiplication Theory

I am working with 2 arrays list1 = ["x","y"] list2 = [ ["5","6","7"],["20","21","22"]] My goal is to create an array of objects like this: [ {list1: x , list2: 5}, {list1: x , list2: 6}, {list1: x , list2: 7}, {list1: y , list2: 20}, {list1: y , l ...

Adjust the height setting of the React-Highcharts viewport

My initial configuration for highcharts looks like this:- function getInitialHighChartsConfig(chartType) { return { credits: false, chart: { type: chartType, height: 325, }, title: { text: '', useHTML: tr ...

Component does not display dynamically created DOM elements

I have a function that creates dynamic DOM elements like this: const arrMarkup = []; const getMarkup = () => { if (true) { arrMarkup.push( <Accordion expanded={expanded === cust.name} onChange={handleChange(cust.name)}> ...

rearrange results in ng-repeat based on specified array in AngularJS

Currently delving into Angularjs and have a quick query: I recently received an array from a user which looks like this: userPreferences = [7,5,4] Additionally, I am working with an object that uses ng-repeat to showcase various news items. The object s ...

Click to toggle information using Jquery

I am attempting to create a button that, when clicked, will toggle between displaying temperature in Fahrenheit and Celsius. While I have been able to make it work initially, the toggle only occurs once and then stops. I have experimented with separate if ...

Basic color scheme

I'm attempting to change the background color behind a partially transparent .png div. The CSS class that modifies the div is ".alert". Manually editing the .alert class background color works perfectly, and now I want to automate this on a 1-second c ...

Is there a way to enable hover functionality on mobile devices? I wish for the hover effect seen on desktop to be triggered automatically on mobile devices

I attempted to implement @media (hover: hover) without success. In my design, I have three images in a row that reveal a text overlay when hovered over with a mouse. However, the issue arises when I try to switch to a mobile view, as the images remain un ...

The shader on the background plane takes precedence over all other elements in three.js

I'm struggling to achieve a simple setup in my scene where a plane serves as the background with a shader, and a box is placed on top with a lambert material. Despite my efforts, I can't seem to make both the plane and the box appear together. An ...

What is the best way to interact with my component in React?

As a newcomer to Reactjs, I have a question regarding my current setup: The components in my project include navComponent.js, stackComponent.js, and nav.js I am trying to pass data from stackComponent.js to navComponent.js so that the nav.js data can be ...

Disregard periods in URLs when configuring nginx servers

While developing with Vite in development mode via Docker on my Windows 10 machine, I encountered an issue where the local custom domain would not load due to a required script failing to load. The specific script causing the problem is /node_modules/.vit ...

The sidebar stays fixed in place and doesn't adapt to varying screen resolutions

Check out my website at . I have a fixed, blue sidebar on the left side of the page to ensure its content is always visible. However, I'm facing an issue with smaller resolutions like 1024x768 where some bottom content is cut off. How can I adjust the ...

Troubleshooting: jQuery $.post not functioning as expected in certain circumstances

I'm currently experimenting with inserting data into a MySQL database using AJAX and jQuery's $.post method. To test this functionality, I have created the following setup: In my index.html file (which already includes jQuery for various other f ...

transform constant values into API requests using React

The sample dataset mentioned will be retrieved from a backend API call handled by Flask. The API has already been configured on the backend. const rows = [ { name: "XYZ", age: "12", email: "<a href="/cdn-cgi/l/emai ...

Is it possible to selectively implement a transition in VueJS based on certain conditions?

My goal is to design an alert box component with a customizable reveal transition, which can be optional. Here's a simplified version of what I have in mind: <template> <transition v-if="withTransition"> <b-alert v-bind="th ...

Is there a way to remove specific elements from an array without using jQuery?

I've recently started diving into Javascript, experimenting with Tampermonkey scripts for the past week. The webpage I'm currently working on features dynamic elements that appear randomly with each page load. Sometimes only one element like "he ...

Unexpected security question arising from vue-CLI output

As I work on my Vue.js application, I've encountered a sudden issue with vue-cli producing error messages that raise concerns about potential malicious dependencies. Executing npm run serve (vue-cli serve) appears to be successful, but it generates m ...

Using AngularJS: Implementing ng-include with a custom function

When using ng-include, I have encountered a peculiar issue. I am attempting to retrieve the template path by invoking a function defined in the controller that returns the path based on the parameter passed. Below is my code snippet: <tr ng-repeat="det ...

When a property is designated as readonly in a TypeScript class, it can still be modified despite its intended

I'm currently grappling with the concept of the readonly keyword in TypeScript. As far as I understand, a readonly property should not be able to be written to after the constructor is called. However, in my testing, I've found that I can actuall ...

Manipulating arrays of objects using JavaScript

I am working with an array of objects represented as follows. data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },] My goal is to transform this data into an array of arrays like the one shown below. [ [{a: 'amb',b: [1], c ...

Ensure the presence of a value in an array using Angular

I need to check if any of the "cuesData" have values or lengths greater than 0. However, in my current code, I can only evaluate the first array and not the rest. https://i.sstatic.net/bMpvg.jpg TS checkValues(values) { const result = Object.values ...