Vue服务端渲染-路由相关
生活随笔
收集整理的這篇文章主要介紹了
Vue服务端渲染-路由相关
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Vue服務端渲染-路由相關
跟CSR項目一樣,同樣使用vue-router來為SSR項目創建路由。
import VueRouter from "vue-router"; import Vue from "vue"; import Home from './pages/home.vue'; import About from './pages/about.vue'; Vue.use(VueRouter);export default () => {return new VueRouter({mode:"history",routes:[{path:"/",component: Home,name:"home"},{path:"/about",component: About,name:"about"}]}) }同時需要在app.js文件中對路由進行注入。
import Vue from 'vue'; import App from './App.vue'; import CreateRouter from './router';export function createApp() {const router= CreateRouter();const app = new Vue({router,render: (h) => h(App),});return {app,}; }在服務端也要實現路由的邏輯。
entry-server.js
最后在server.js服務文件中對路由進行匹配
app.get('*', (req, res) => {if(req.url == '/main.js') {const file = fs.readFileSync('./dist/main.js');res.send(file);return;}const template = fs.readFileSync('./dist/index.html', 'utf-8');const bundle = require('./dist/vue-ssr-server-bundle.json');const render = createBundleRenderer(bundle, {template: template,});render.renderToString(req, (err, html) => {console.log(err);console.log(html);if (err) {if (err.code === 404) {res.status(404).end('Page not found')} else {res.status(500).end('Internal Server Error')}} else {res.end(html)}}); });路由懶加載
import VueRouter from "vue-router"; import Vue from "vue"; import Home from './pages/home.vue'; import About from './pages/about.vue'; Vue.use(VueRouter);export default () => {return new VueRouter({mode:"history",routes:[{path:"/",component: () => import('./pages/home.vue'),name:"home"},{path:"/about",component: () => import('./pages/about.vue'),name:"about"}]}) }在打包出來的文件可以看到多了兩個文件
- distpages_about_vue.jspages_home_vue.js當訪問對應的頁面時,才會請求對應的js的文件,這樣有助于減少瀏覽器在初始渲染中下載的資源體積。
需要注意的是,你仍然需要在掛載 app 之前調用 router.onReady,因為路由器必須要提前解析路由配置中的異步組件,才能正確地調用組件中可能存在的路由鉤子。
entry-client.js
import { createApp } from './app'; const { app, router } = createApp(); router.onReady(() => {app.$mount('#app') })總結
以上是生活随笔為你收集整理的Vue服务端渲染-路由相关的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows下如何打开CSV文件
- 下一篇: 小童学习MOS管