简体   繁体   中英

How to download a local CSV file from a vue.js webpage?

I'm new to vue.js and I am mainly wondering how I can have my webpage display a download link for downloading a csv file that I have stored locally.

I have created a component Template.vue. Inside it I have

<a :href="item.loc" download>  {{item.title}} </a>

And in the export I have this:

export default {
  name: 'Template',
  data () {
    return {
      item: {loc: require("../assets/example.csv")}
    }
  }
}

At the moment this doesn't work for CSV-files. I received the following error when I tried to run this code with a CSV-file:

"./src/assets/example.csv Module parse failed: Unexpected token (1:14) You may need an appropriate loader to handle this file type."

However, if I would try to download an image(png) then it works. How do I go about implementing a loader? Or are there other ways to solve my problem?

Are you using vue-cli? If you do i guess you could do something like

import csvFile from "../assets/example.csv"

export default {
  name: "Template",
  data() {
    return {
      item: csvFile
    }
  }
}

// in your template

<a :href="item"> </a>

If your csv-file isn't dynamically generated, you could probably use it as a static asset and just link to it's path. It's been a while since i've done anything with Vue, but according to a quick glance at the docs i think you can put your csv file into your static folder and reference it like this:

<a href="./assets/example.csv">{{someTitle}}</a>

Link to docs: https://cli.vuejs.org/guide/html-and-static-assets.html#disable-index-generation

I found this answer :

1)-Install the loader with npm i csv-loader -D 2)-add this code into the vue.config.js file:

module.exports = {
       chainWebpack: config => {
        config
          .module
          .rule('csv')
          .test(/\.csv$/)
          .use('csv-loader')
          .loader('csv-loader')
          .options({
             dynamicTyping: true,
             header: true,
            skipEmptyLines: true
          })
           .end()
   }
}

3)-then you can import local files into your components,the file will automatically be converted to a js object:

    import csv from './assets/file.csv'
    export default{
      created(){
        console.log(csv)
    }
  }

and here is a link to the answer: https://www.fabiofranchino.com/log/include-csv-in-vue-cli-project/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM