首页 > 解决方案 > 如何在外部 json 文件上为 Vue js 上的 Web 应用程序最终构建创建 require 函数?

问题描述

我正在构建一个仅在机器上本地服务的测验网络应用程序。现在所有的逻辑和架构都完成了。但剩下的唯一问题是:我如何使“questionOptions.js”中的问题列表在生产版本中成为外部的?这样我就可以更改列表而无需导出另一个构建版本?

目前,该列表正在以开发模式从本地提取,我不知道将列表加载为动态(可以在最终构建时进行编辑)。

Vue.js

var looper = new Vue({
  el: "#quiz",
  data: {
    questionList: require("./js/questionsOptions"),
    currentQuestion: 0,
    ...
  }
});

questionOptions.js

module.exports = [
  {
    title: "Soalan 1",
    questionTitle: 'Ini adalah penyata soalan 1',
    correctAnswer: true,
    answerSelection: [
      {
        name: "Answer 1 A",
        score: true
      },
      {
        name: "Answer 1 B",
        score: false
      },
    ]
  },
  {
    title: "Soalan 2",
    questionTitle: 'Ini adalah penyata soalan 2',
    correctAnswer: true,
    answerSelection: [
      {
        name: "Answer 2 A",
        score: true
      },
      {
        name: "Answer 2 B",
        score: false
      }
    ]
  }
]

我将来可能想更改列表内容或长度,仅在最终版本中更改问题列表。我怎样才能做到这一点?

标签: javascriptvuejs2

解决方案


require() is synchronous and executes at build time.

To perform an async request at runtime, you can use import(). Keep in mind, your app will need to be able to handle the asynchronous loading.

For example

data: {
  questionList: [],
  currentQuestion: 0,
},
async created () {
  this.questionList = await import(
    /* webpackChunkName: "questionOptions" */
    './js/questionsOptions'
  )
}

推荐阅读