To use Vue.js with server-side rendering (SSR), you can follow the steps below:
Install the necessary dependencies:
npm install vue vue-server-renderer express
Create a new file for your server code (e.g., server.js
).
Import the required modules:
const express = require('express');
const Vue = require('vue');
const renderer = require('vue-server-renderer').createRenderer();
Create an express app:
const app = express();
Define a route to handle rendering:
app.get('/', (req, res) => {
// Create a new Vue instance
const app = new Vue({
template: `<div>Hello World</div>`
});
// Render the Vue instance to HTML
renderer.renderToString(app, (err, html) => {
if (err) {
console.error(err);
res.status(500).end('Internal Server Error');
}
// Send the rendered HTML to the client
res.end(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue SSR Example</title>
</head>
<body>${html}</body>
</html>
`);
});
});
Start the server:
app.listen(3000, () => {
console.log(`Server started at http://localhost:3000`);
});
Run the server:
node server.js
Now, if you visit http://localhost:3000
, you should see "Hello World" displayed on the page. This is a basic example of using Vue.js with server-side rendering (SSR). You can customize it further by using a router, Vuex store, or other Vue.js components.