Lesson 14-Vue3 Advanced Application Development

Server-Side Rendering (SSR)

Core Concepts and Advantages of SSR

SSR Workflow:

  1. Client request reaches the server.
  2. Server renders Vue components into HTML.
  3. Sends complete HTML to the client.
  4. Client performs “hydration” to enable interactivity.

Core Advantages Comparison:

FeatureSSRCSR
First Screen Load SpeedFast (Direct HTML)Slow (Requires JS Download)
SEO FriendlinessHigh (Complete HTML Content)Low (Initial Empty Page)
Server LoadHigh (Renders per Request)Low (Static Files)
InteractivityAvailable After HydrationImmediately 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:

FeatureasyncDatafetch
Execution TimingBefore Component CreationAfter Component Creation
Return ValueMerged into Component DataPopulates Store or Context
Error HandlingThrows Error, Interrupts RenderingHandleable via try/catch
Applicable ScenariosMandatory DataOptional 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:

  1. XSS Protection: Automatic HTML escaping
  2. CSRF Protection: Request origin validation
  3. 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:

  1. Pre-render all pages during build.
  2. Generate pure static HTML files.
  3. Deploy to CDN or static hosting services.

Applicable Scenarios Comparison:

ScenarioSSG SuitabilitySSR 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:

  1. Use <ClientOnly> to wrap interactive components.
  2. Defer loading non-critical resources.
  3. Implement lazy loading and compression for images.
  4. 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:

StrategyImplementationApplicable Scenarios
Message CompressionUse gzip/MessagePackLarge data transfers
Throttling & DebouncingLimit event trigger frequencyHigh-frequency interactions
Batch UpdatesCombine multiple state changesComplex component states
Selective SubscriptionReceive updates on-demandLarge 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:

  1. JWT token verification
  2. WebSocket connection authentication
  3. 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:

  1. Encrypted transmission of sensitive data
  2. Input validation and filtering
  3. Anti-DDoS attack mechanisms
  4. 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.

Share your love