gpt4 book ai didi

javascript - 使用Vue读取当前目录下的文件

转载 作者:行者123 更新时间:2023-11-29 23:06:16 30 4
gpt4 key购买 nike

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

<!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文件。

<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 的内容如下。

hello

最佳答案

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

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

  1. 安装 raw-loader来自 NPM:

    npm i -D raw-loader
  2. <projectroot>/vue.config.js , 配置 Webpack 使用 raw-loader对于 *.txt :

    module.exports = {
    //...
    chainWebpack: config => {
    config.module
    .rule('raw')
    .test(/\.txt$/)
    .use('raw-loader')
    .loader('raw-loader')
    .end()
    },
    }
  3. 在您的组件的 .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>

关于javascript - 使用Vue读取当前目录下的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54697757/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com