Vue.js实现PDF新窗口打开报错求助:点击按钮重复渲染首页
Let's break down why your button is reloading the home page instead of opening your resume PDF, and fix it up step by step:
Why This Is Happening
- Incorrect Static Asset Handling: Vue CLI projects have specific rules for static resources. If your PDF is just sitting in the root of your project folder (not in the
publicdirectory), Webpack won't recognize it as a static asset. When you use./Avi-Dave-Resume.pdf, it’s a relative path that resolves based on your current route. For example, if you’re on the home route (/), it tries/Avi-Dave-Resume.pdf—but if you navigate to another route like/about, it would incorrectly try/about/Avi-Dave-Resume.pdfinstead. Since that path doesn’t exist, your Vue router falls back to the home page (likely from a wildcard route like*pointing to your home component). - Redundant
target="_blank": Thetargetattribute on your button doesn’t affect thewindow.open()call in your method—you need to specify the target directly in the JavaScript instead.
Step-by-Step Fixes
Move Your PDF to the
publicFolder
Vue CLI’spublicdirectory is reserved for unprocessed static assets. Files here get copied directly to the root of your build output, so their paths stay consistent. DragAvi-Dave-Resume.pdfinto your project’spublicfolder.Update the
openPdfMethod
Use an absolute path (starting with/) to point directly to the PDF in thepublicfolder, and explicitly set the target to_blankto ensure it opens in a new window:openPdf() { window.open('/Avi-Dave-Resume.pdf', '_blank'); }Clean Up the Button Markup
Since we’re handling the target in JS, you can remove the redundanttarget="_blank"attribute from the button to keep your code clean:<button class="button in-left2" v-on:click="openPdf()">Resume</button>
Quick Validation Checks
- Double-check the filename in
publicmatches exactly (case-sensitive on Linux/macOS—Avi-Dave-Resume.pdfvsavi-dave-resume.pdfare treated as different files!). - Test accessing
http://localhost:8080/Avi-Dave-Resume.pdfdirectly in your browser—if it loads, your path is correct; if not, reconfirm the file’s location in thepublicfolder.
内容的提问来源于stack exchange,提问作者Avi Dave

