You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Vue.js结合raw-loader读取更新后的日志文件内容

解决Vue组件动态读取更新后log.txt文件的问题

Ah, I see the issue here! The problem with your current approach is that raw-loader handles the file import at compile time, not runtime. When you import logs with !!raw-loader!log.txt, Webpack embeds the contents of log.txt directly into your bundled JavaScript during the build process. That means even if you update log.txt later, the logs variable will always hold the old, compiled-in content—calling getLog() just reassigns that stale value.

To fix this, you need to fetch the file dynamically at runtime instead of using a static import. Here's how to adjust your component:

Step 1: Remove the static raw-loader import

You don't need the import logs from '!!raw-loader!log.txt'; line anymore, since we'll fetch the file on demand.

Step 2: Update the getLog method to use HTTP requests

Use the browser's native fetch API (or Axios if you prefer) to fetch the latest content of log.txt every time the button is clicked. We'll add a cache-busting parameter (like a timestamp) to ensure the browser doesn't return a cached version of the file.

Here's the revised component code:

<template>
  <div>
    <button @click="getLog">Refresh Logs</button>
    <pre>{{ log }}</pre>
  </div>
</template>

<script>
export default {
  data() {
    return {
      log: ""
    };
  },
  mounted() {
    this.getLog(); // Load initial logs on mount
  },
  methods: {
    async getLog() {
      try {
        // Add a timestamp parameter to bypass browser cache
        const response = await fetch(`log.txt?t=${Date.now()}`);
        if (!response.ok) {
          throw new Error(`Failed to fetch logs: ${response.statusText}`);
        }
        this.log = await response.text();
      } catch (error) {
        console.error(error);
        this.log = "Error loading logs!";
      }
    }
  }
};
</script>

Why this works:

  • Every time you click the button, fetch sends a fresh request to your server for log.txt
  • The t=${Date.now()} parameter ensures the URL is unique each time, so the browser won't use a cached copy of the file
  • We use async/await for cleaner asynchronous code, but you could also use .then() if you prefer

Optional enhancements:

  • If you want to automate updates later, you could add a setInterval(this.getLog, 5000) in the mounted hook to refresh logs every 5 seconds
  • For real-time updates without polling, you could look into using WebSockets (if your server supports it) to push log changes to the client

内容的提问来源于stack exchange,提问作者Mueyiwa Moses Ikomi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 12:57:27