Server-Side Rendering (SSR)
Core Concepts and Advantages of SSR
SSR Workflow:
- Client request reaches the server.
- Server renders Vue components into HTML.
- Sends complete HTML to the client.
- Client performs “hydration” to enable interactivity.
Core Advantages Comparison:
| Feature | SSR | CSR |
|---|---|---|
| First Screen Load Speed | Fast (Direct HTML) | Slow (Requires JS Download) |
| SEO Friendliness | High (Complete HTML Content) | Low (Initial Empty Page) |
| Server Load | High (Renders per Request) | Low (Static Files) |
| Interactivity | Available After Hydration | Immediately Available |
Nuxt.js SSR Configuration Example:
// nuxt.config.js
export default {
ssr: true,
target: 'server',
head: {
titleTemplate: '%s - My SSR Application'
},
render: {
compressor: {
threshold: 0 // Enable Gzip compression
}
}
}
Nuxt.js Routing Management
File-Based Routing:
pages/
├── index.vue # /
├── about.vue # /about
├── users/
│ ├── index.vue # /users
│ └── _id.vue # /users/:id
Dynamic Route Parameter Retrieval:
<!-- pages/users/_id.vue -->
<script setup>
const route = useRoute()
const userId = route.params.id // Retrieve dynamic parameter
// Server-side data prefetching
definePageMeta({
async asyncData({ params }) {
const user = await fetchUser(params.id)
return { user }
}
})
</script>
Data Prefetching and State Synchronization
asyncData vs. fetch Comparison:
| Feature | asyncData | fetch |
|---|---|---|
| Execution Timing | Before Component Creation | After Component Creation |
| Return Value | Merged into Component Data | Populates Store or Context |
| Error Handling | Throws Error, Interrupts Rendering | Handleable via try/catch |
| Applicable Scenarios | Mandatory Data | Optional Data/Side Effects |
State Synchronization Example:
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
async increment() {
this.count = await api.getCounter()
}
}
})
// Page component
definePageMeta({
async asyncData({ store }) {
await store.dispatch('counter/increment')
}
})
SSR Performance Optimization Strategies
Caching Strategy Implementation:
// serverMiddleware/cache.js
import LRU from 'lru-cache'
const ssrCache = new LRU({
max: 100, // Maximum cache items
maxAge: 1000 * 60 * 15 // 15-minute cache
})
export default function cacheMiddleware(req, res, next) {
const key = req.url
if (ssrCache.has(key)) {
res.send(ssrCache.get(key))
return
}
res.originalSend = res.send
res.send = (body) => {
ssrCache.set(key, body)
res.originalSend(body)
}
next()
}
Component-Level Caching:
<!-- components/ProductList.vue -->
<script setup>
import { useCache } from '~/composables/useCache'
const { cachedData } = useCache('products', () => fetchProducts())
</script>
SSR Security and Error Handling
Security Measures:
- XSS Protection: Automatic HTML escaping
- CSRF Protection: Request origin validation
- Sensitive Data Filtering: Server-side data sanitization
Error Handling Example:
// plugins/error-handler.js
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.hook('app:error', (err) => {
console.error('Application-level error:', err)
sendErrorToMonitoring(err)
})
nuxtApp.vueApp.config.errorHandler = (err, context) => {
console.error('Component error:', err)
context.$toast.error('An error occurred, please try again')
}
})
Static Site Generation (SSG)
Core Concepts and Applicable Scenarios of SSG
SSG Workflow:
- Pre-render all pages during build.
- Generate pure static HTML files.
- Deploy to CDN or static hosting services.
Applicable Scenarios Comparison:
| Scenario | SSG Suitability | SSR Suitability |
|---|---|---|
| Blog/Documentation Sites | ★★★★★ | ★★☆☆☆ |
| E-commerce Product Pages | ★★★☆☆ | ★★★★☆ |
| User Dashboards | ★☆☆☆☆ | ★★★★★ |
| Marketing Landing Pages | ★★★★☆ | ★★★☆☆ |
VuePress Theme Development
Custom Theme Structure:
my-theme/
├── layouts/
│ ├── Layout.vue # Main layout
│ └── 404.vue # Error page
├── components/
│ ├── Sidebar.vue # Sidebar
│ └── Navbar.vue # Navbar
├── styles/
│ ├── index.scss # Global styles
│ └── palette.scss # Color variables
└── index.js # Theme entry
Theme Configuration Example:
// themes/my-theme/index.js
export default {
extend: '@vuepress/theme-default',
layouts: {
Layout: path.resolve(__dirname, './layouts/Layout.vue'),
404: path.resolve(__dirname, './layouts/404.vue')
}
}
Content Management and Dynamic Routing
Markdown Content Enhancement:
---
title: Advanced Vue Techniques
date: 2023-01-01
tags: [vue, ssr]
---
::: tip Tip
This is a custom container
:::
```vue
<template>
<div>Embedded Vue example code</div>
</template>
Dynamic Route Generation:
// .vuepress/config.js
module.exports = {
themeConfig: {
nav: [
{ text: 'Guide', link: '/guide/' },
{ text: 'API', link: '/api/' }
],
sidebar: {
'/guide/': [
'', // guide/index.md
'ssr', // guide/ssr.md
'ssg' // guide/ssg.md
]
}
}
}
SSG Performance Optimization
Incremental Static Regeneration (ISR):
// vue.config.js
module.exports = {
pluginOptions: {
ssg: {
// Enable ISR
interval: 60, // Regenerate every 60 seconds
exclude: ['/admin'] // Exclude specific routes
}
}
}
Pre-rendering Optimization Techniques:
- Use
<ClientOnly>to wrap interactive components. - Defer loading non-critical resources.
- Implement lazy loading and compression for images.
- Apply code splitting and tree shaking.
SSG and CMS Integration
Headless CMS Configuration Example:
// plugins/cms.js
export default defineNuxtPlugin(async () => {
const { $config } = useNuxtApp()
const cms = new CMSClient($config.cmsApiKey)
// Fetch content
const posts = await cms.getPosts()
return { posts }
})
CMS Content Rendering:
<template>
<div v-for="post in posts" :key="post.id">
<h2>{{ post.title }}</h2>
<div v-html="post.content"></div>
</div>
</template>
Real-Time Application Development
WebSocket Integration with Vue
WebSocket Encapsulation Example:
// composables/useWebSocket.js
export function useWebSocket(url) {
const socket = ref(null)
const messages = ref([])
const isConnected = ref(false)
const connect = () => {
socket.value = new WebSocket(url)
socket.value.onopen = () => {
isConnected.value = true
}
socket.value.onmessage = (event) => {
messages.value.push(JSON.parse(event.data))
}
socket.value.onclose = () => {
isConnected.value = false
// Auto-reconnect logic
setTimeout(connect, 5000)
}
}
const send = (data) => {
if (socket.value?.readyState === WebSocket.OPEN) {
socket.value.send(JSON.stringify(data))
}
}
onMounted(connect)
onUnmounted(() => socket.value?.close())
return { messages, isConnected, send }
}
GraphQL and Apollo Client
Apollo Client Configuration:
// apollo.js
import { ApolloClient, InMemoryCache } from '@apollo/client/core'
import { createApolloProvider } from '@vue/apollo-option'
const cache = new InMemoryCache()
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache
})
export const apolloProvider = createApolloProvider({
defaultClient: client
})
Usage in Vue Component:
<script setup>
import { useQuery } from '@vue/apollo-composable'
import gql from 'graphql-tag'
const { result, loading, error } = useQuery(gql`
query GetUser($id: ID!) {
user(id: $id) {
name
email
}
}
`, { id: '123' })
</script>
Real-Time Collaborative Editing Implementation
CRDT Algorithm Application:
// Using Yjs library for collaborative editing
import * as Y from 'yjs'
import { WebsocketProvider } from 'y-websocket'
const ydoc = new Y.Doc()
const provider = new WebsocketProvider(
'ws://localhost:1234',
'room-name',
ydoc
)
const ytext = ydoc.getText('document')
const textarea = document.querySelector('textarea')
// Sync local edits
textarea.addEventListener('input', e => {
const newValue = e.target.value
Y.applyUpdate(ydoc, Y.encodeStateAsUpdate(ydoc))
})
// Receive remote updates
provider.on('sync', (isSynced) => {
if (isSynced) {
const state = provider.getUpdate()
Y.applyUpdate(ydoc, state)
}
})
Real-Time Communication Performance Optimization
Optimization Strategies Comparison:
| Strategy | Implementation | Applicable Scenarios |
|---|---|---|
| Message Compression | Use gzip/MessagePack | Large data transfers |
| Throttling & Debouncing | Limit event trigger frequency | High-frequency interactions |
| Batch Updates | Combine multiple state changes | Complex component states |
| Selective Subscription | Receive updates on-demand | Large datasets |
WebSocket Connection Optimization:
// Heartbeat mechanism
setInterval(() => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ type: 'heartbeat' }))
}
}, 30000)
// Bandwidth adaptation
function adjustQuality() {
const connectionSpeed = calculateConnectionSpeed()
if (connectionSpeed < 1000) {
setVideoQuality('low')
} else {
setVideoQuality('high')
}
}
Real-Time Application Security Controls
Authentication and Authorization Solutions:
- JWT token verification
- WebSocket connection authentication
- Operation permission checks
Security Implementation Example:
// WebSocket authentication middleware
wss.on('connection', (ws, req) => {
const token = req.url.split('token=')[1]
if (!verifyToken(token)) {
ws.close(1008, 'Unauthorized')
return
}
// Handle messages after authorization
ws.on('message', (message) => {
const data = JSON.parse(message)
if (!hasPermission(token, data.action)) {
ws.send(JSON.stringify({ error: 'Forbidden' }))
return
}
// Process legitimate requests...
})
})
Data Security Measures:
- Encrypted transmission of sensitive data
- Input validation and filtering
- Anti-DDoS attack mechanisms
- Regular security audits
By systematically applying these advanced application development techniques, developers can build high-performance, real-time, and secure Vue 3 applications. It’s recommended to select appropriate technical solutions based on specific business needs and stay updated with the latest developments in the Vue ecosystem.



