使用Vue读取当前目录中的文件 [英] Read file inside current directory using Vue

查看:148
本文介绍了使用Vue读取当前目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取文本文件数据,该文件位于我的.vue文件所在的目录中.但这并不会同时在chrome和firefox上返回文本.相反,它返回以下响应,这不是我的文本文件的内容.

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>

以下是我的vue文件.

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>

hello.txt的内容如下.

Contents of hello.txt are following.

hello

推荐答案

我假设您正在使用Webpack,因为您有一个 .vue 文件(需要 vue-加载程序 Webpack插件)...

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

您可以使用 raw-loader 进行加载 .txt 文件作为字符串.

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

  1. 使用以下命令从NPM安装 raw-loader :

npm i -D raw-loader

  • < projectroot>/vue.config.js中 ,将Webpack配置为对 *.txt 使用 raw-loader :

    module.exports = {
      //...
      chainWebpack: config => {
        config.module
          .rule('raw')
          .test(/\.txt$/)
          .use('raw-loader')
          .loader('raw-loader')
          .end()
      },
    }
    

  • 在组件的 .vue 文件中,使用 import require 加载 hello.txt :

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

  • 这篇关于使用Vue读取当前目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆