如何用Vue.js结合raw-loader读取更新后的日志文件内容
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,
fetchsends a fresh request to your server forlog.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/awaitfor 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 themountedhook 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

