You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Vue.js中通过字符串拼接实现JSON文件动态名称导入

Solution for Dynamic JSON Import in Vue.js

Hey there! The problem you're facing is that static import statements are resolved at compile time, not when your app runs. That means you can't use variables directly in the import path like you tried—webpack (or whatever bundler you're using) needs to know exactly which files to bundle ahead of time.

Here are two reliable ways to handle dynamic JSON imports in Vue:

1. Use the Dynamic import() Function

The dynamic import() function works at runtime and returns a Promise, so you can use it to load your JSON file once your component mounts (or whenever you need it):

<template>
  <!-- Render the JSON data once it's loaded -->
  <div v-if="myJson">{{ JSON.stringify(myJson, null, 2) }}</div>
  <div v-else>Loading data...</div>
</template>

<script>
export default {
  data() {
    return {
      date: '2018-05-18',
      myJson: null // Initialize as null until the JSON loads
    };
  },
  async mounted() {
    // Build the file path dynamically using your date variable
    const filePath = `./2018-05-at-${this.date}.json`;
    
    // Wait for the dynamic import to complete
    const jsonModule = await import(filePath);
    
    // JSON files are exported as the default module, so we access .default
    this.myJson = jsonModule.default;
  }
};
</script>

Quick Notes:

  • Vue CLI projects support dynamic imports out of the box—no extra config needed.
  • We use async/await here for clean, readable code, but you could also chain .then() if you prefer.

2. Preload JSON Files with require.context

If you have multiple JSON files in the same directory and want to avoid dynamic code splitting, use webpack's require.context to preload all relevant files upfront. This lets you access any of them dynamically later:

<script>
// Create a context that includes all JSON files in the current directory
const jsonFileContext = require.context('./', false, /\.json$/);

export default {
  data() {
    return {
      date: '2018-05-18',
      myJson: null
    };
  },
  mounted() {
    const fileName = `2018-05-at-${this.date}.json`;
    
    // Fetch the preloaded JSON file from the context
    const jsonModule = jsonFileContext(`./${fileName}`);
    this.myJson = jsonModule.default;
  }
};
</script>

Breaking Down require.context:

  • First argument: The directory to search (.\/ for the current component's directory).
  • Second argument: false tells it not to search subdirectories.
  • Third argument: A regex to match file names (/\.json$/ targets all .json files).

Why Your Original Code Failed

Static import statements are processed before your app runs, so the bundler can't resolve variables like date—it needs a hardcoded path. Dynamic imports or require.context work around this by handling file loading at runtime, when your variables are available.

内容的提问来源于stack exchange,提问作者Imperatura

火山引擎 最新活动