Home > database >  Accessing html elements with $refs returns different than document.getElementById()
Accessing html elements with $refs returns different than document.getElementById()

Time:04-13

I have two components, A and B. Component A has a programatically generated svg that is appended to a div that has (ref="graph"). Component B has a link that uppon click downloads this svg to a file.

The problem I ran into is the following : If I plave the link and the svg in the same component, then this portion of code works fine

    var svg = document.getElementById("graph");
    var serializer = new XMLSerializer();
    var source = serializer.serializeToString(svg);

Now, if i place the link in a component different from the one where is located the svg, and change the code as following. Then I will get an error.

var svg =this.$refs.graph; 
var serializer = new XMLSerializer();
var source = serializer.serializeToString(svg);

TypeError: Failed to execute 'serializeToString' on 'XMLSerializer': parameter 1 is not of type 'Node'.

I have no clue what I am doing wrong here.

CodePudding user response:

Please could I encourage you to include your components and templates as it's a lot harder to debug tiny snippets of code without their wider context.

That being said, it looks like you are trying to access Component A's ref from Component B, which is not possible.

You are better off emitting the event in Component B and handling it in Component A:

Component A

<template>
  <div>
    <div ref="graph"></div>
    <!-- make this link invisible using position absolute, opacity: 0 etc -->
    <a ref="svglink" download="testSvg.svg" />
    <ComponentB @export="downloadSvg" />
  </div>
</template>

<script>
export default {
  methods: {
    downloadSvg() {
      var svg = this.$refs.graph;
      var serializer = new XMLSerializer();
      var source = serializer.serializeToString(svg);
      this.$refs.svglink.href = someLink;
      this.$refs.svglink.click();
      // ...
    }
  }
}  
</script>

Component B

<template>
  <a @click.prevent="$emit('export')">EXPORT SVG</a>
</template>

CodePudding user response:

The problem was in fact a component hierarchy problem. Since the link was placed in a child component of the image. I simply had to add $parent as :

ar svg =(this.$parent.$refs.graph); 
var serializer = new XMLSerializer();
var source = serializer.serializeToString(svg);
  • Related