Vue.js - A reactivity component that does not require constant re-rendering

I am encountering an issue with the reactivity of two components, namely line-chart and bar-chart.

When I modify the checkbox value linked to v-model="formChart.type", the components line-chart and bar-chart are automatically re-rendered.

However, when I click on the button that triggers the functions submitForm, generateChart(), and resetTypeChart(), those components do not re-render.

The mounted() function is not being called.

I am puzzled as to why this is happening despite resetting both the type and show. I have tried using Vue.set but it did not make any difference.

The code does reach the resetTypeChart() function.


Inconsistency in Component Rendering

<div class="chart-container">
      <line-chart v-if="formChart.type === 'line_chart' && formChart.show" :chartData="dataChart" ref="lineChart"></line-chart>
      <bar-chart v-if="formChart.type === 'bar_chart' && formChart.show" :chartData="dataChart" ref="barChart"></bar-chart>
  </div>

Checkbox for Changing Chart Type

<el-radio-group size="small" v-model="formChart.type">
     <el-radio-button label="line_chart"> Line Chart </el-radio-button>
     <el-radio-button label="bar_chart"> Bar Chart </el-radio-button>
</el-radio-group>

Button to Generate Chart

<el-button type="primary" size="large"@click="submitForm('formChart')">Generate</el-button>

submitForm(formName) {
   this.$refs[formName].validate((valid) => {
      this.generateChart();
      this.resetTypeChart();
   } 
});

Function for Resetting the Chart (Attempt)

resetTypeChart () {
  const saveType = this.formChart.type;
  this.formChart.type = '';
  this.formChart.show = false;
  Vue.set(this.formChart, 'type', saveType);
  this.formChart.type = saveType;
  this.formChart.show = true;
 }

JSFIDDLE

  • Selecting Bar Chart generates the component.
  • Clicking on Generate while staying on the same radio button results in nothing shown.

https://jsfiddle.net/rd3ahxp8/3/

Answer №1

The lack of an alert popping up upon clicking the generate button is due to Vue determining that no real changes have occurred, thus there is no need to update the DOM. As mentioned earlier in the comments, Vue's DOM updates occur asynchronously, meaning it only checks for changes after your method has finished executing. Since nothing substantial has changed in your state once the method is complete - as you simply toggle between values - there is no visible difference.

To illustrate this point, I made adjustments to your fiddle by introducing a time delay before resetting the values. By allowing Vue enough time to detect the change and revert back, you will see the expected outcome.

generateChart : function () {
    alert('generate')
    const saveType = this.formChart.type;
    this.formChart.type = '';
    this.formChart.show = false;
    setTimeout(()=>{
        this.formChart.type = saveType;
      this.formChart.show = true;

    }, 1000)
}

In your scenario, an update should be triggered when something within dataChart changes, prompting a re-render in Vue. However, if there are no alterations and you intend to maintain the same chart display, there might not be a pressing need for a re-render.

To ensure your chart refreshes with changes in chartData, consider watching the chartData property within your components. Below is a comprehensive example demonstrating how this can be implemented.

// Code here

For a visual representation of charts updating on click of the generate button, refer to this accompanying fiddle.

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 Unable to execute function in Internet Explorer 11

I'm experiencing an issue where this script works in Google Chrome but not in IE 11. Can anyone explain why?: <script type="text/javascript"> window.onload = function () { var ammount = document.getElementById('ammount'); var price = ...

Attempting to devise a jQuery algorithm sorting method

To enhance the answer provided in this post: How to stack divs without spaces and maintain order on smaller screens using Bootstrap I've been exploring ways to develop a jQuery script that dynamically adjusts the margin-top of div elements based on t ...

Difficulty encountered in concealing X and Y axes for stacked area chart in Angular NVD3 charts

I recently ran an example from Angular NVD3's 'live edit' section, which is available at the following link: After running it in Plunkr using this link: Stacked Area Chart, I followed the documentation instructions to hide the x and y axes ...

Combine all div elements to create a unified image and then proceed to save it as a jpg file before uploading to the server

These are the divs below: <div style="width:800px; height:420px; position:absolute; top:0px; left:0px; z-index:10; background-image: url('https://3t27ch3qjjn74dw66o1as187-wpengine.netdna-ssl.com/wp-content/uploads/2016/05/052516-800x420-vege-Wallp ...

How to extract and display data when clicking on a Bootstrap switch

I have integrated BootStrap Switch like this: <?php while ($arr = mysql_fetch_array($res)) { ?> <td class="center"> <?php if ($arr['status'] == 1) { ?> <input class="switch" type="checkbo ...

Utilizing Ionic to seamlessly integrate Firebase into a factory, maintaining separation of controllers and services within distinct files

I'm struggling with setting up a firebase factory for use in my controllers. Currently, this is how my code appears: index.html ... <!-- integrating firebase --> <script src="lib/firebase/firebase.js"></script> <script src="lib/ ...

Is it possible to include personalized validations in Formik's YupValidationSchema?

Is it possible to include custom validations in Formik's YupValidationSchema as shown below? YupValidationSchema = () => { return Yup.object({ Email: Yup.string() .max(256, "Length exceed 256 chars") ...

Ways to access elements and their associated values in a JavaScript Array

I'm facing a challenge with a JavaScript array where I need to extract teams (Team A, Team B) and organize them into one array while preserving their order. See below for the current output of the array, as well as the JS code provided and the expecte ...

Front-end procedural logic for increasing identification values

$scope.items.push({ "itemId": $scope.tabId + 1, "itemName" : itemName, }); Whenever I try to push the item, I always console.log($scope.itemId) but it remains the same without increasing. One way to handle this issue could be utilizing $http after each ...

Do you have to change the style of each individual element using JavaScript, or is there another method to accomplish this?

Recently, I've been exploring different ways to use JavaScript to globally adjust styles. My goal is to modify the CSS rule that controls the element's style, similar to how you can do it using the Inspector in Webkit. However, after visiting htt ...

Why is my React component not being updated with Routes?

I'm new to using react-router and I'm struggling with it for the first time. Here is the code snippet: App.tsx import React from 'react'; logo = require('./logo.svg'); const { BrowserRouter as Router, Link, Route } = require ...

Achieving dynamic serving of static files using Rollup and integrating seamlessly with node-resolve

Currently, I am in the process of building a library using TSDX, which is a powerful CLI tool for package development based on Rollup. My project involves a collection of country flags SVGs that need to be imported and displayed dynamically when required. ...

Utilizing nested v-for in Vue.js with lodash's groupBy function

When fetching data from a database, I am using lodash groupby to group my data like so: var vm = this axios.get(this.buildURL()) .then(function(response) { Vue.set(vm.$data, 'model', response.data.model) vm.groupData = _.groupBy(vm.model ...

Creating a React Component in TypeScript that utilizes Promise Objects for data handling

After receiving a Promise type Object as a response, an error has been encountered: Error: Objects are not valid as a React child (found: object with keys { key1, key2, key3 ...}... How can this issue be resolved? // Component.tsx import React, { us ...

JavaScript Arrays with Four Dimensions

Looking for a solution to generate arrays with any number of dimensions, including 4D arrays. I'm interested in being able to use the function to create an array and then access it like this: arr[3][2][23][12] = "amazing"; ...

Unable to insert a JSON object into an Array

This might appear to be a duplicate, but it's not. None of the solutions I've tried have worked. Within my angular module, I have a list: this.checkedInterviews = [] Followed by a function that does the following: var interviewModel = { ...

Looking for assistance with transferring a data attribute to a form redirection

I'm seeking assistance with a coding dilemma I've encountered. To provide some background, I have a list of items on my website, each featuring a 'Book Now' button that redirects users to different pages. Recently, I incorporated a mod ...

Click event to verify, delete, and include class identifier in angular13

Looking to enhance functionality by dynamically adding and removing the 'active' class to 'li a' elements on click. While the current code performs well when clicking from top to bottom, it fails to work in reverse order. component.htm ...

Why is my jQuery $.ajax success function not providing any results?

When checking the Network tab in Chrome, I noticed that the correct data (action, username, password) is being sent, but the message is not returning to $('#return_login'). Can anyone spot what might be wrong with my code? Below is the jQuery co ...

Prevent my application from being idle (Cordova/Android)

I have recently developed an Android app using a node.js webpack project. After installing the app on my phone, I observed that it enters a sleep mode along with the phone. Consequently, a JavaScript timer I set up stops functioning as intended: pingTime ...