vue2使用了插件prerender-spa-plugin-next,预渲染基本没问题,但是不能读取到动态数据
vue.config.js
const { defineConfig } = require("@vue/cli-service");
const PrerenderSPAPlugin = require("prerender-spa-plugin-next");
const path = require("path");
const fs = require("fs");
const RouteResourcePreloadPlugin = require("@route-resource-preload/webpack-plugin");
const port = process.env.port || process.env.npm_config_port || 80; // 端口
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
host: "0.0.0.0",
port: port,
open: true,
proxy: {
[process.env.VUE_APP_BASE_API]: {
target: `http://localhost:8081`,
changeOrigin: true,
pathRewrite: {
["^" + process.env.VUE_APP_BASE_API]: "",
},
},
},
},
configureWebpack: {
plugins: [
// 预渲染
new PrerenderSPAPlugin({
staticDir: path.join(__dirname, "dist"),
routes: [
'/',
'/news-center',
'/overseas-warehouse',
'/north-america',
'/about-us',
...JSON.parse(fs.readFileSync(path.resolve(__dirname, 'public/news-ids.json'), 'utf8')).map(id => `/news-center/news-details/${id}`)
],
rendererOptions: {
inject: {},
headless: false,
timeout: 5000,
renderAfterTime: 10000,
renderAfterDocumentEvent: "render-event",
pretty: true,
devtools: true,
},
postProcess: function (context) {
const titles = {
"/": "Home",
"/news-center": "News Center",
"/north-america": "North America",
"/about-us": "About Us",
"/overseas-warehouse": "Overseas Warehouse",
};
if (context.route.startsWith('/news-center/news-details/')) {
const id = context.route.split('/').pop();
titles[context.route] = `News Details - ${id}`;
}
context.html = context.html.replace(
/<title>[^<]*<\/title>/i,
"<title>" + (titles[context.route] || "Document") + "</title>"
);
},
}),
// 预加载
new RouteResourcePreloadPlugin({
modulePreloadMap: {
"/HomeLoad": ["src/components/Home"],
"/AmericaLoad": ["src/components/NorthAmerica"],
"/WarehouseLoad": ["src/components/OverseasWarehouse"],
"/AboutLoad": ["src/components/AboutUs"],
"/CenterLoad": ["src/components/NewsCenter"],
"/DetailsLoad": ["src/components/NewsDetails"], // 修改为正确的路径
},
mfPreloadMap: {},
assetPreloadMap: {},
}),
],
},
});
vue组件是
<template>
<div id="contentBox">
<div id="navbarOther">
<Navbar class="navbarOther-navbar" />
</div>
<div id="back">
<div>
<el-button
type="primary"
class="back-button"
@click="goBack"
icon="el-icon-arrow-left"
>返回列表</el-button
>
</div>
</div>
<div id="content">
<div id="newsHead">
<h1 class="title">{{ content.title }}</h1>
<p class="date">{{ content.date }}</p>
</div>
<div v-html="content.content" class="content-div"></div>
</div>
<Foot />
</div>
</template>
<script>
import Navbar from "@/components/Navbar.vue";
import Foot from "@/components/Foot.vue";
import { getNewsInfo } from "../api/news";
var _hmt = _hmt || [];
(function () {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?66b6397027a120b4b7a90787267949b4";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
export default {
components: {
Navbar,
Foot,
},
props: ["id"],
data() {
return {
news: {
title: "",
},
newsId: this.id,
content: {},
windowWidth: 0,
windowHeight: 860,
};
},
async mounted() {
// 初始滚动位置
window.scrollTo(0, 0);
// 设置窗口尺寸
this.getWindowWidth();
try {
// 获取数据并确保 DOM 更新
await this.getNews(); // 获取新闻数据
await this.$nextTick(); // 等待 DOM 更新
// 在 DOM 完全准备好后触发 render-event
document.dispatchEvent(new Event("render-event"));
} catch (error) {
// 捕获并打印任何错误
console.error("Error during mounted lifecycle:", error);
}
},
methods: {
getWindowWidth() {
this.windowWidth = window.innerWidth; // 获取窗口宽度
this.windowHeight =
window.innerWidth / 2 - 80 > 860 ? 860 : window.innerWidth / 2 - 80;
},
async getNews() {
try {
const response = await getNewsInfo(this.id);
if (response && response.data && response.data.data) {
this.content = response.data.data;
console.log("this.content",this.content)
} else {
console.warn("Unexpected response structure:", response);
// 设置合理的默认值
this.content = {
title: "Default Title1",
date: "N/A1",
content: "<p>No content available1.</p>",
};
}
} catch (error) {
console.error("Error fetching news:", error);
// 设置合理的默认值
this.content = {
title: "Default Title",
date: "N/A",
content: "<p>No content available2.</p>",
};
}
},
最后预渲染显示的是 这些内容,但是动态数据是读取的到的
// 设置合理的默认值
this.content = {
title: "Default Title1",
date: "N/A1",
content: "<p>No content available1.</p>",
};