【问题标题】:Transform words from file to array in Vue.js在 Vue.js 中将单词从文件转换为数组
【发布时间】:2021-08-25 20:58:54
【问题描述】:

我创建了一个 Vue 应用,目前遇到以下问题:

我有一个包含不同单词的给定文件。
我可以根据需要自定义文件格式,但是Markdowntext file 会更好。
该文件位于App.vue 文件的旁边 --> 在.src 中。

例如,此文件包含以下内容:

Test1
Test2
Test3
Test4

现在我想将这 4 个单词放入一个数组中。
我在App.vue 中的代码如下所示:

<template>
    ...
</template
<script>
    import { computed, ref } from 'vue'
    import someStuff from './components/SomeStuff'
    ...

    // here I want to in put the words
    const words= [];
    // here a random word is selected from this array
    // this works so far when I manually enter words to my array
    const randomWord = () => words[Math.floor(Math.random() * words.length)];
    export default {
        components: { SomeStuff },
        setup() { ...

这是我迄今为止尝试过的:

var fs = require('fs');
var array = fs.readFileSync('./src/MyDataSet.txt').toString().split("\n");
for(i in words) {
    console.log(words[i]);
}

只有我不知道如何将这个 JS sn-p 包含在我的 Vue 组件中。
require() 没有定义,我想我不能把这段代码放在那里。
我不想拥有任何库、插件或其他依赖项。

【问题讨论】:

    标签: javascript arrays vue.js file


    【解决方案1】:

    您可以将其作为方法添加到脚本标签中

    <script>
    import Vue from "vue";
    
    export default Vue.extend({
      data() {
        return {
          wordArray: [],
        };
      },
      props: {},
      methods: {
            readWords() {
             var fs = require('fs');
             var array = fs.readFileSync('./src/MyDataSet.txt').toString().split("\n");
            
             this.wordArray.push(array)
          }
    <script>
    

    然后你在代码中的任何地方调用你的函数,它会填充“wordArray”,这样你就可以以任何你想要的方式使用它。

    【讨论】:

    • 感谢您的回答。那么如果我在export defaults 之外定义了我的单词数组,它是如何工作的呢?我已经在调用 randomWordwords 等的默认值中包含了方法。
    【解决方案2】:

    fs 模块仅在服务器端有用。 您可以使用marked 或类似的库。

    请参考此链接。 https://www.npmjs.com/package/marked

    【讨论】:

      【解决方案3】:

      我现在已经解决了如下问题。当然,这不是最好或最优化的解决方案,但它似乎可以工作并覆盖大写。

      我写了一个新函数,相应地创建了一个新文件并导入它,以便我可以在本地调用该函数。

      解决方案现在如下所示:

      <template>
          ...
      </template>
      
      <script>
          import SomeStuff from "./components/SomeStuff";
          import generateWords from "./Dataset";
      
          const words = generateWords();
          const randomWort = () => words[Math.floor(Math.random() * words.length)];
          ...
      </script>
      

      这就是新的Dataset.js 文件:

      export default function generateWords() {
          return [
              "Test1",
              "Test2",
              "Test3",
              "Test4"
          ]
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-26
        • 1970-01-01
        • 2013-11-27
        • 1970-01-01
        • 2017-12-15
        • 2023-03-23
        • 2010-11-07
        相关资源
        最近更新 更多