Read file inside current directory using Vue

可紊 提交于 2021-02-10 08:38:30

问题


I'm trying to get text file data located in the same directory where my .vue file is. But it's not returning the text on both chrome and firefox. Instead it's returning following response, which is not the content of my text file.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>router-project</title>
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  <script type="text/javascript" src="/app.js"></script></body>
</html>

Following is my vue file.

<template>
  <body>
    <div> hello world </div>
  </body>
</template>

<script>
var $ = require('jquery');
window.jQuery = $;

export default {
  data () {
    return {
    }
  },
  created () {
    this.getPoemList(),
  },

  methods: {
   getPoemList () {

      function reqListener () {
         console.log(this.responseText);
      }

      var oReq = new XMLHttpRequest();
      oReq.addEventListener("load", reqListener);
      oReq.open("GET", "hello.txt");
      oReq.send();


    }   // getPoemList function ends
  }     // methods end
}       // export default ends
</script>

<style scoped>
</style>

Contents of hello.txt are following.

hello

回答1:


I assume you're using Webpack, since you have a .vue file (requiring the vue-loader Webpack plugin)...

You can use raw-loader to load the .txt file as a string.

  1. Install raw-loader from NPM with:

    npm i -D raw-loader
    
  2. In <projectroot>/vue.config.js, configure Webpack to use raw-loader for *.txt:

    module.exports = {
      //...
      chainWebpack: config => {
        config.module
          .rule('raw')
          .test(/\.txt$/)
          .use('raw-loader')
          .loader('raw-loader')
          .end()
      },
    }
    
  3. In your component's .vue file, use import or require to load hello.txt:

    <script>
    import helloText from './hello.txt';  // OR: const helloText = require('./hello.txt')
    
    export default {
      //...
      methods: {
        getPoemList () {
          console.log({ helloText });
        }
      }
    }
    </script>
    


来源:https://stackoverflow.com/questions/54697757/read-file-inside-current-directory-using-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!