Home > Blockchain >  How to download a file on a link click in Nuxt?
How to download a file on a link click in Nuxt?

Time:05-24

I'm coming across an edge case issue where if a user navigates around a few Nuxt routes, clicks the websites "logo" which is an anchor tag back home, then clicks the browsers native back button and then finally clicks a link which is supposed to open a pdf, it redirects to my 404 page.

If the user clicks the pdf link upon page load it behaves as expected. Not sure what is going on here? I tried to add a method to force window.open on the pdf and it is still broken.

Anchor example:

<a
  
  @click.prevent="forceHrefToPdf('Instructions.pdf')"
>
  Instructions 
</a>

Method:

forceHrefToPdf(pdf) {
  window.open(pdf, "_blank")
}

PDF is inside the /root/static directory.

CodePudding user response:

Try this one maybe

<template>
  <button @click="downloadMe">download me</button>
</template>

<script>
export default {
  methods: {
    downloadMe() {
      const link = document.createElement('a')
      link.href = '/Instructions.pdf'
      link.download = 'Intructions.pdf'
      link.target = '_blank'
      link.click()
    },
  },
}
</script>

Also, do not use an a tag, it's meant to move from page to page. Rather please use a button who is aimed at doing an action like downloading a PDF. Your client is not the one to decide if it's a link or not (implementation details should not matter here).


Of course, this is also totally feasible but not recommended regarding a11y.

<a href="/Instructions.pdf" target="_blank" download>
  Download my PDF via a link tag
</a>
  • Related