How to refresh an existing d3 graph without generating a new one within vue 3

I have a Vue app that utilizes d3 to create rectangles within a child component.

The number of rectangles created is dependent on the values within the data property of the parent.
Modifying the data will update the existing rectangles in the child component.

After updating the data, the correct number of rectangles corresponding to the data are displayed.
My goal is to prevent the creation of a new "g" element each time.

One solution I have considered so far involves using d3.remove to delete the existing "g" element if an update occurs and then creating a new one.

// Parent Component

<template>
  <Child :data="data" />

  <button type="button" @click="changeData">Click to Change</button>
</template>

<script>
import Child from "./components/Child.vue";

export default {
  name: "App",
  components: {
    Child,
  },

  data() {
    return {
      data: [1],
    };
  },

  methods: {
    changeData() {
      this.data = [1, 2];
    },
  },
};
</script>



// Child Component

<template>
  <div class="foo">
    <svg ref="svgRef"></svg>

    <h1>I Have This Prop</h1>
  </div>
</template>

<script>
import d3 from "@/assets/d3";

import { onMounted, ref, watchEffect } from "@vue/runtime-core";

export default {
  name: "Circles",
  props: ["data"],

  setup(props) {
    const svgRef = ref(null);

    onMounted(() => {
      watchEffect(() => {
        const selectSvg = d3.select(svgRef.value);

        selectSvg

          .selectAll("g")
          .data(Object.values(props.data))
          .join("g")

          .attr("transform", (d, i) => `translate(60, ${i * 21})`)
          .append("rect")
          .attr("width", 20 + "px")
          .attr("height", 20 + "px")
          .attr("fill", d3.color("orange"));
      });
    });

    return { svgRef };
  },
};
</script>

<style scoped>
.limit {
  max-width: 100px;
}
</style>



Answer №1

To easily delete a rect element by its class, you can simply add a specific class to it.

Then, to remove only the rect elements with that class, use the following code:

d3.select(".specific-class").remove();

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 Browserify on files that have already been browserified

When trying to use browserify to require an already browserified module, I am running into an issue where the bundle cannot resolve the module that has already been browserified. For instance, I have a file called bundle-1.js that was bundled using the co ...

What steps do I need to take to execute a script that utilizes the mootools library within an asp.net environment

I've been working on a website that includes a mail form. I'm using the Mootools 1.4.3 library along with FormCheck 1.6.js. However, when I click the button, nothing happens except for the page refreshing. I really like this form and want to make ...

Using jQuery to retrieve a file that has been uploaded through an input field with the type of 'file'

I am looking to extract the file that has been uploaded using an <input type='file'> tag. Currently, when I use $('#inputId').val(), it only retrieves the name of the file, not the actual content of the file itself. I came acros ...

When using react, it is not possible to have a <span> element as a child of a <

I designed a custom select dropdown feature for use in a redux-form within a react-redux application. The dropdown functions well, with no performance issues, but I am encountering a warning in the browser. Warning: validateDOMNesting(...): <span> c ...

Associate JSON sub-string with corresponding main parent

I am working with a JSON string that is generated from an API. [{"categories":{"category":{"id":"1","Name":"fruit"}}},{"categories":{"category":{"id":"2","Name":"veg"}}},{"products":{"product":{"id":"1","Name":"fruit"}}},{"products":{"product":{"id":"2"," ...

What could be causing the issue when trying to sort a list by the difference between two fields?

Currently, I have a list of items with like and dislike buttons attached to each one. My goal is to organize this list based on the total score, which is calculated by subtracting the number of dislikes from the number of likes. I am facing some challenge ...

The issue I am facing is with the post_logout_redirect_uri not functioning properly when using localStorage in an OIDC Auth

authority: 'yyy', client_id: this.'yyy', redirect_uri: 'http://localhost:4200/login', response_type: 'token', scope: 'yyy', post_logout_redirect_uri: & ...

Middleware triggered for error management but failing to deal with response

My issue lies in handling errors by returning JSON. My error handler, while being called and logging in the console, doesn't return the expected output. Here is the code for the handler: const handleError = function(err, req, res, next) { console ...

I encountered an issue where videos won't autoplay in the vue-slick-carousel

Software: NUXT SSR. Description: We are looking to incorporate video playback within a carousel component. When users interact with the carousel by clicking next/prev or directly on the video, it should play and pause upon repeated clicks. Our approach in ...

Struggling to Load: Ajax Request to Google App Engine Causing Page to

I have developed a page that communicates with a Python application running on Google App Engine to retrieve JSON data using JSONP for cross-origin functionality. However, I am encountering an issue where the page hangs and fails to display the data no mat ...

Error in JavaScript Slideshow

I am attempting to create a slider that changes with a button click. Below is my JavaScript code: var img1=document.getElementById("p1"); var img2=document.getElementById("p2"); var img3=document.getElementById("p3"); function slide(){ ...

The text box isn't displaying the value, even though it was functioning properly just two days back

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> function insertParamIntoField(anchor, param, field) { ...

Exploring the interactive doughnut graph using SVG and Vue.js

Looking to create a unique dynamic donut chart using SVG and Vue. I want it to mirror the exact SVG format found on this webpage: (To see the animated chart, select a dish and click on ingredients) This might not have been the best approach, but it was ...

Transmit JSON data through a REST API request body

Looking to send a JSON request via REST, with client code in Node.js and server code in Golang. The structure of the body is as follows: const query = "{\"query\":\"query {n result: application(id: \"fb7b5992-4d0a-4782-acb7-13ae6cc66 ...

What is the process for disabling the CSS module feature in Next.js?

In Next.js, Global CSS can only be imported in _App.js. However, importing global CSS in every component is not allowed, so we have to use CSS modules to comply with this restriction imposed by Next.js. Currently, I am in the process of migrating a large ...

Quasar 2 + Apollo: Uh oh! There seems to be an issue with the Apollo client. The client with id default cannot be found. If you're setting up outside of

Just went through the instructions on https://github.com/quasarframework/app-extension-apollo/tree/v2 to add the Apollo extension to Quasar 2.4.9: "devDependencies": { "@babel/eslint-parser": "^7.13.14", "@quasa ...

ag-Grid Vue - How to wrap text in headers and cells

Can anyone provide guidance on wrapping text in both headers and cells for ag-grid vuejs? I've included an example of my code below: https://codesandbox.io/embed/x98omwov3o ...

The Vue application successfully compiles but fails to load in the web browser

Upon running npm run serve on my Vue app, the console displays the following output: DONE Compiled successfully in 17450ms 2:15:55 PM App running at: - Local: ...

Creating a custom filter with ngx-pagination

Having trouble with filtering in Angular 7 + Electron 4 while using ngx-pagination. I followed the steps mentioned in the documentation, but encountered an error Uncaught Error: Template parse errors: The pipe 'stringFilter' could not be found ...

Tips for retrieving a value from fs.accessAsync function

I am currently working on verifying the accessibility of a specific file, folder, or directory for reading purposes. I have implemented the code below, which functions properly. However, there are a couple of aspects that I would like to inquire about: 1. ...