Vue怎样进行服务端渲染,操作过程是什么
Admin 2022-08-11 群英技术资讯 276 次浏览
概念:放在浏览器进行就是浏览器渲染,放在服务器进行就是服务器渲染。
yarn add vue-server-renderer vue yarn add koa koa-router
createRenderer,创建一个渲染函数 renderToString, 渲染出一个字符串
const Vue = require('vue'); const render = require('vue-server-renderer'); const Koa = require('koa'); const Router = require('koa-router'); const app = new Koa(); const router = new Router(); const vm = new Vue({ data(){ return {msg:"hello world"} }, template:`<div>{{msg}}</div>` }); router.get('/',async (ctx)=>{ let r = await render.createRenderer().renderToString(vm); ctx.body = ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> ${r} </body> </html> ` }); app.use(router.routes()); app.listen(4000);
<!DOCTYPE html> <html lang="en"> <head><title>Hello</title></head> <body> <!--vue-ssr-outlet--> </body> </html>
传入template 替换掉注释标签
const Vue = require('vue'); const render = require('vue-server-renderer'); const Koa = require('koa'); const Router = require('koa-router'); const app = new Koa(); const router = new Router(); const vm = new Vue({ data(){ return {msg:"hello world"} }, template:`<div>{{msg}}</div>` }); const template = require('fs').readFileSync('./index.html','utf8'); router.get('/',async (ctx)=>{ let r = await render.createRenderer({ template }).renderToString(vm); ctx.body = r; }); app.use(router.routes()); app.listen(4000);
├── config │ ├── webpack.base.js │ ├── webpack.client.js │ └── webpack.server.js ├── dist │ ├── client.bundle.js │ ├── index.html │ ├── index.ssr.html │ ├── server.bundle.js │ ├── vue-ssr-client-manifest.json │ └── vue-ssr-server-bundle.json ├── package.json ├── public │ ├── index.html │ └── index.ssr.html ├── server.js ├── src │ ├── App.vue │ ├── components │ │ ├── Bar.vue │ │ └── Foo.vue │ ├── entry-client.js │ ├── entry-server.js │ ├── app.js │ ├── router.js │ └── store.js ├── webpack.config.js
安装插件
yarn add webpack webpack-cli webpack-dev-server vue-loader vue-style-loader css-loader html-webpack-plugin @babel/core @babel/preset-env babel-loader vue-template-compiler webpack-merge
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const VueLoaderPlugin = require('vue-loader/lib/plugin') const resolve = (dir)=>{ return path.resolve(__dirname,dir) } module.exports = { entry: resolve('./src/client-entry.js'), output:{ filename:'[name].bundle.js', path:resolve('dist') }, module:{ rules:[ { test:/.css$/, use:['vue-style-loader','css-loader'] }, { test:/.js$/, use:{ loader:'babel-loader', options:{ presets:['@babel/preset-env'] } }, exclude:/node_modules/ }, { test:/.vue$/, use:'vue-loader' } ] }, plugins:[ new VueLoaderPlugin(), new HtmlWebpackPlugin({ template:'./index.html' }) ] }
import Vue from "vue"; import App from "./App.vue"; export default () => { // 为了保证实例的唯一性所以导出一个创建实例的函数 const app = new Vue({ render: h => h(App) }); return { app }; };
import createApp from "./app"; const { app } = createApp(); app.$mount("#app"); // 客户端渲染手动挂载到dom元素上
import createApp from "./app"; export default () => { const { app } = createApp(); return app; // 服务端渲染只需将渲染的实例导出即可 };
let path = require('path'); let VueLoaderPlugin = require('vue-loader/lib/plugin') module.exports = { output:{ filename:'[name].bundle.js', path:path.resolve(__dirname,'../dist') }, module:{ rules:[ {test:/.css/,use:['vue-style-loader','css-loader']}, { test:/.js/, use:{ loader:'babel-loader', options:{ presets:['@babel/preset-env'] }, }, exclude:/node_modules/, }, {test:/.vue/,use:'vue-loader'} ] }, plugins:[ new VueLoaderPlugin() ] }
const merge = require("webpack-merge"); const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const base = require("./webpack.base"); const resolve = filepath => { return path.resolve(__dirname, filepath); }; module.exports = merge(base, { entry: { client: resolve("../src/client-entry.js") }, plugins: [ new HtmlWebpackPlugin({ template: resolve("../template/index.client.html") }) ] });
const merge = require("webpack-merge"); const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const base = require("./webpack.base"); const resolve = filepath => { return path.resolve(__dirname, filepath); }; module.exports = merge(base, { entry: { server: resolve("../src/server-entry.js") }, target: "node", output: { libraryTarget: "commonjs2" // 导出供服务端渲染来使用 }, plugins: [ new HtmlWebpackPlugin({ filename: "index.ssr.html", template: resolve("../template/index.ssr.html"), excludeChunks: ["server"] }) ] });
"scripts": { "client:dev": "webpack-dev-server --config ./build/webpack.client.js", // 客户端开发环境 "client:build": "webpack --config ./build/webpack.client.js", // 客户端打包环境 "server:build": "webpack --config ./build/webpack.server.js" // 服务端打包环境 },
在App.vue上增加id="app"可以保证元素被正常激活
const Koa = require("koa"); const Router = require("koa-router"); const static = require("koa-static"); const path = require("path"); const app = new Koa(); const router = new Router(); const VueServerRenderer = require("vue-server-renderer"); const fs = require("fs"); // 服务端打包的结果 const serverBundle = fs.readFileSync("./dist/server.bundle.js", "utf8"); const template = fs.readFileSync("./dist/index.ssr.html", "utf8"); const render = VueServerRenderer.createBundleRenderer(serverBundle, { template }); router.get("/", async ctx => { ctx.body = await new Promise((resolve, reject) => { render.renderToString((err, html) => { // 必须写成回调函数的方式否则样式不生效 resolve(html); }); }); }); app.use(router.routes()); app.use(static(path.resolve(__dirname, "dist"))); app.listen(3000);
在index.ssr.html中需要手动引入客户端打包后的结果
实现热更新,自动增加preload和prefetch,以及可以使用sourceMap
const VueSSRClientPlugin = require('vue-server-renderer/client-plugin'); // 在客户端打包时增加插件 const VueSSRServerPlugin = require('vue-server-renderer/server-plugin'); // 在服务端打包时增加插件 const Koa = require("koa"); const Router = require("koa-router"); const static = require("koa-static"); const path = require("path"); const app = new Koa(); const router = new Router(); const VueServerRenderer = require("vue-server-renderer"); const fs = require("fs"); // 服务端打包的结果 // const serverBundle = fs.readFileSync("./dist/server.bundle.js", "utf8"); const template = fs.readFileSync("./dist/index.ssr.html", "utf8"); const serverBundle = require("./dist/vue-ssr-server-bundle.json"); const clientManifest = require("./dist/vue-ssr-client-manifest.json"); const render = VueServerRenderer.createBundleRenderer(serverBundle, { template, clientManifest // 自动注入客户端打包后的文件 }); router.get("/", async ctx => { ctx.body = await new Promise((resolve, reject) => { render.renderToString((err, html) => { // 必须写成回调函数的方式否则样式不生效 resolve(html); }); }); }); app.use(router.routes()); app.use(static(path.resolve(__dirname, "dist"))); app.listen(3000);
yarn add vue-router
import Vue from "vue"; import VueRouter from "vue-router"; import Foo from "./components/Foo.vue"; Vue.use(VueRouter); export default () => { const router = new VueRouter({ mode: "history", routes: [ { path: "/", component: Foo }, { path: "/bar", component: () => import("./components/Bar.vue") } ] }); return router; };
导出路由配置
import Vue from "vue"; import App from "./App.vue"; import createRouter from "./router"; export default () => { const router = createRouter(); const app = new Vue({ router, render: h => h(App) }); return { app, router }; };
<template> <div id="app"> <router-link to="/"> foo</router-link> <router-link to="/bar"> bar</router-link> <router-view></router-view> </div> </template>
router.get("*", async ctx => { ctx.body = await new Promise((resolve, reject) => { render.renderToString({ url: ctx.url }, (err, html) => { // 必须写成回调函数的方式否则样式不生效 resolve(html); }); }); });
export default ({ url }) => { return new Promise((resolve, reject) => { const { app, router } = createApp(); router.push(url); router.onReady(() => { const matchComponents = router.getMatchedComponents(); if (!matchComponents.length) { return reject({ code: 404 }); } resolve(app); }, reject); }); }; // 服务器可以监控到错误信息,返回404 render.renderToString({ url: ctx.url }, (err, html) => { // 必须写成回调函数的方式否则样式不生效 if (err && err.code == 404) { resolve("404 Not Found"); } resolve(html); });
yarn add vuex
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default ()=>{ let store = new Vuex.Store({ state:{ username:'song' }, mutations:{ changeName(state){ state.username = 'hello'; } }, actions:{ changeName({commit}){ return new Promise((resolve,reject)=>{ setTimeout(() => { commit('changeName'); resolve(); }, 1000); }) } } }); return store }
// 引用vuex import createRouter from './router'; import createStore from './store' export default ()=>{ let router = createRouter(); let store = createStore(); let app = new Vue({ router, store, render:(h)=>h(App) }) return {app,router,store} }
import createApp from './main'; export default (context)=>{ return new Promise((resolve)=>{ let {app,router,store} = createApp(); router.push(context.url); // 默认访问到/a就跳转到/a router.onReady(()=>{ let matchComponents = router.getMatchedComponents(); // 获取路由匹配到的组件 Promise.all(matchComponents.map(component=>{ if(component.asyncData){ return component.asyncData(store); } })).then(()=>{ context.state = store.state; // 将store挂载在window.__INITIAL_STATE__ resolve(app); }); }) }) }
// 在浏览器运行代码 if(typeof window !== 'undefined' && window.__INITIAL_STATE__){ store.replaceState(window.__INITIAL_STATE__); }
export default { mounted() { return this.$store.dispatch("changeName"); }, asyncData(store) { return store.dispatch("changeName"); } };
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
JavaScript即将推出两个新的数据类型:Record 和 Tuple ,这俩是啥呢?其实就是一个只读的 Object 和 Array,其实在其它语言中已经有类似的数据类型了,例如 Python 中也有 Tuple(元祖)这一类型,作用也是一个只读的数组(在Python里叫只读的列表),一起来了解一下,这个特性是一个第2阶段提案(即差不多稳了),想要提前体验的,文末也有 polyfill 的使用教程!
这篇文章主要介绍了如何在JavaScript中使用localStorage,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
这篇文章主要介绍了JavaScript 定时器,在JavaScript中定时器有两个 setInterval() 与 setTimeout() 分别还有取消定时器的方法,下面来看看文章的详细介绍
这篇文章主要为大家详细介绍了原生JavaScript实现轮播图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
微信小程序滚动定位的效果如何实现?滚动定位的效果也就是点击小程序导航标签会滚动定位到对应位置,具体实现效果如下。那么这个效果该怎样做呢?接下来我们一起来了解看看实现代码。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008