Home > database >  Changing html element attribute using vue $refs
Changing html element attribute using vue $refs

Time:04-13

I am trying to access the href attribute of a link element in a distant componant. The @click func will generate a new href and then place it in the link element.

Here is my current link:

 <a ref="svglink" href="javascript:void(0)"  @click="saveSvg2" download="testSvg.svg" >EXPORT SVG</a>


 

I try to place the new url like this:

this.$refs.svglink.href = url;
```
But I get a "Property 'href' does not exist on type 'Vue'" message from my IDE and the code is not working.

What am I doing wrong?

CodePudding user response:

Firstly, you should use ref="svglink" instead of id="svglink" if you want to use a ref.

However, there's a better way than this by using reactive properties.

<template>
  <a id="svglink" :href="url"  @click="saveSvg2" download="testSvg.svg" >EXPORT SVG</a>
</template>

<script>
export default {
  data() {
    return {
      url: ''
    }
  },
  mounted() {
    // whenever you update this.url the link will update
    // doesn't have to be in mounted(), this is just an example
    this.url = 'http://example.com'
  }
}
</script>
  • Related