前端使用nuxt.js的seo优化

Nuxt.js 前端 SEO 优化全面指南

Nuxt.js 是 Vue.js 的框架,提供了开箱即用的服务端渲染(SSR)和静态站点生成(SSG)功能,天生对 SEO 友好。以下是针对 Nuxt.js 的详细 SEO 优化方案。

一、Nuxt.js 的 SEO 优势

  1. 服务端渲染(SSR) :服务器返回完整的 HTML,爬虫可直接索引内容
  2. 静态站点生成(SSG) :预渲染为静态 HTML,速度极快
  3. 自动优化:Nuxt 自动处理许多 SEO 基础工作

二、基础配置优化

1. Nuxt 配置中的 SEO 设置

javascript

css 复制代码
// nuxt.config.js
export default {
  // 全局 SEO 配置
  app: {
    head: {
      htmlAttrs: {
        lang: 'zh-CN'
      },
      meta: [
        { charset: 'utf-8' },
        { name: 'viewport', content: 'width=device-width, initial-scale=1' },
        { 
          name: 'description', 
          content: '你的网站描述,这里应该详细描述你的网站内容' 
        },
        // Open Graph 协议(社交媒体分享)
        { property: 'og:type', content: 'website' },
        { property: 'og:title', content: '你的网站标题' },
        { property: 'og:description', content: '分享时的描述' },
        { property: 'og:image', content: '/og-image.jpg' },
        // Twitter Card
        { name: 'twitter:card', content: 'summary_large_image' },
        // 其他 meta 标签
        { name: 'robots', content: 'index, follow' },
        { name: 'author', content: '你的品牌/公司名' }
      ],
      link: [
        { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
        // 预连接重要域名
        { rel: 'preconnect', href: 'https://fonts.googleapis.com' },
        { rel: 'dns-prefetch', href: 'https://fonts.googleapis.com' },
        // 规范链接
        { rel: 'canonical', href: 'https://your-domain.com' }
      ],
      script: [
        // JSON-LD 结构化数据(也可放在组件中)
        {
          type: 'application/ld+json',
          innerHTML: JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'WebSite',
            'name': '你的网站名称',
            'url': 'https://your-domain.com'
          })
        }
      ]
    }
  }
}

2. 路由和 URL 优化

javascript

javascript 复制代码
// nuxt.config.js
export default {
  // 使用友好的 URL
  routeRules: {
    // 为特定路由设置规则
    '/products/:id': { prerender: true },
    '/blog/**': { swr: 3600 } // 静态再生
  },
  
  // 配置路由过渡
  router: {
    trailingSlash: true, // 统一尾部斜杠
    scrollBehavior(to, from, savedPosition) {
      // 控制页面滚动行为,改善用户体验
      if (savedPosition) {
        return savedPosition;
      } else {
        return { top: 0 };
      }
    }
  }
}

三、页面级 SEO 优化

1. 使用 useHead 组合式 API(推荐)

vue

xml 复制代码
<!-- pages/blog/[slug].vue -->
<script setup>
const route = useRoute();
const { data: article } = await useFetch(`/api/articles/${route.params.slug}`);

// 动态设置页面 SEO 信息
useHead({
  title: article.value.title + ' | 网站名称',
  meta: [
    { 
      name: 'description', 
      content: article.value.excerpt || article.value.content.substring(0, 160) 
    },
    { 
      name: 'keywords', 
      content: article.value.tags?.join(', ') || '' 
    },
    // Open Graph
    { property: 'og:title', content: article.value.title },
    { property: 'og:description', content: article.value.excerpt },
    { property: 'og:image', content: article.value.image },
    // 规范链接
    { rel: 'canonical', href: `https://your-domain.com/blog/${article.value.slug}` }
  ],
  // 结构化数据
  script: [
    {
      type: 'application/ld+json',
      innerHTML: JSON.stringify({
        '@context': 'https://schema.org',
        '@type': 'BlogPosting',
        'headline': article.value.title,
        'description': article.value.excerpt,
        'image': article.value.image,
        'author': {
          '@type': 'Person',
          'name': article.value.author
        },
        'datePublished': article.value.published_at,
        'dateModified': article.value.updated_at
      })
    }
  ]
});
</script>

<template>
  <article>
    <!-- 正确的标题结构 -->
    <h1>{{ article.title }}</h1>
    <h2>{{ article.subtitle }}</h2>
    
    <!-- 面包屑导航 -->
    <nav aria-label="面包屑导航">
      <ol>
        <li><NuxtLink to="/">首页</NuxtLink></li>
        <li><NuxtLink to="/blog">博客</NuxtLink></li>
        <li>{{ article.title }}</li>
      </ol>
    </nav>
    
    <!-- 内容 -->
    <div v-html="article.content"></div>
    
    <!-- 优化图片 -->
    <NuxtImg
      :src="article.featured_image"
      :alt="article.image_alt || article.title"
      width="800"
      height="600"
      loading="lazy"
      format="webp"
      quality="80"
    />
  </article>
</template>

2. 使用 Nuxt SEO Kit(推荐插件)

bash

bash 复制代码
npm install @nuxt/seo

javascript

css 复制代码
// nuxt.config.js
export default {
  modules: ['@nuxt/seo'],
  
  site: {
    url: 'https://your-domain.com',
    name: '你的网站名称',
    description: '网站描述',
    defaultLocale: 'zh-CN',
    trailingSlash: true,
  },
  
  sitemap: {
    sources: ['/api/__sitemap__/urls']
  },
  
  robots: {
    // 自动生成 robots.txt
    allow: ['*'],
    disallow: ['/admin']
  }
}

四、性能优化

1. 图片优化

vue

xml 复制代码
<!-- 使用 NuxtImg 组件 -->
<template>
  <div>
    <!-- 自动优化图片 -->
    <NuxtImg
      src="/images/hero.jpg"
      alt="描述文字"
      width="1200"
      height="630"
      loading="lazy"
      format="webp"
      :modifiers="{ quality: 80 }"
      sizes="sm:100vw md:50vw lg:400px"
    />
    
    <!-- 使用 NuxtPicture 响应式图片 -->
    <NuxtPicture
      src="/images/hero.jpg"
      alt="描述文字"
      :imgAttrs="{ class: 'responsive-image' }"
    />
  </div>
</template>

2. 资源加载优化

javascript

arduino 复制代码
// nuxt.config.js
export default {
  // 预加载关键资源
  render: {
    resourceHints: true,
    asyncScripts: true
  },
  
  // 字体优化
  font: {
    // 自动预加载关键字体
    inject: true
  }
}

3. 代码分割和懒加载

vue

xml 复制代码
<script setup>
// 组件懒加载
const LazyComponent = defineAsyncComponent(() =>
  import('~/components/HeavyComponent.vue')
);

// 数据懒加载(仅客户端)
const loadHeavyData = () => {
  if (process.client) {
    import('~/utils/heavy-data.js').then(module => {
      // 使用模块
    });
  }
};
</script>

<template>
  <!-- 图片懒加载 -->
  <img
    v-lazy="'/images/product.jpg'"
    alt="产品图片"
  />
  
  <!-- 组件懒加载 -->
  <LazyComponent v-if="showComponent" />
  
  <!-- 视频懒加载 -->
  <video preload="metadata">
    <source src="/video/promo.mp4" type="video/mp4">
  </video>
</template>

五、高级 SEO 功能

1. 生成 XML Sitemap

javascript

xml 复制代码
// server/api/sitemap.xml.ts
export default defineEventHandler(async (event) => {
  const posts = await $fetch('/api/posts');
  
  const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
  <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
      <loc>https://your-domain.com</loc>
      <lastmod>${new Date().toISOString()}</lastmod>
      <changefreq>daily</changefreq>
      <priority>1.0</priority>
    </url>
    ${posts.map(post => `
      <url>
        <loc>https://your-domain.com/blog/${post.slug}</loc>
        <lastmod>${new Date(post.updated_at).toISOString()}</lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
      </url>
    `).join('')}
  </urlset>`;
  
  event.res.setHeader('content-type', 'text/xml');
  return sitemap;
});

2. 自动生成规范链接

vue

xml 复制代码
<script setup>
const route = useRoute();
const config = useRuntimeConfig();

// 自动生成规范链接
const canonicalUrl = computed(() => {
  return `${config.public.siteUrl}${route.path}`.replace(//$/, '');
});

useHead({
  link: [
    { rel: 'canonical', href: canonicalUrl }
  ]
});
</script>

3. 多语言 SEO 优化

javascript

css 复制代码
// nuxt.config.js
export default {
  modules: ['@nuxtjs/i18n'],
  
  i18n: {
    locales: [
      { code: 'zh', iso: 'zh-CN', file: 'zh-CN.js' },
      { code: 'en', iso: 'en-US', file: 'en-US.js' }
    ],
    defaultLocale: 'zh',
    strategy: 'prefix_except_default',
    // 为多语言添加 hreflang
    seo: true,
    
    vueI18n: './i18n.config.ts'
  },
  
  // 多语言 sitemap
  sitemap: {
    i18n: true
  }
}

六、部署优化

1. 缓存策略配置

javascript

arduino 复制代码
// nuxt.config.js
export default {
  // 配置渲染缓存
  nitro: {
    prerender: {
      crawlLinks: true,
      routes: ['/', '/about', '/blog']
    }
  },
  
  // 设置 HTTP 头
  routeRules: {
    '/_nuxt/**': { 
      headers: { 
        'Cache-Control': 'public, max-age=31536000, immutable' 
      } 
    },
    '/images/**': { 
      headers: { 
        'Cache-Control': 'public, max-age=86400' 
      } 
    },
    '/api/**': { 
      cors: true,
      headers: { 
        'Access-Control-Allow-Origin': '*' 
      } 
    }
  }
}

2. 使用 Nuxt Security 增强安全性

javascript

arduino 复制代码
// nuxt.config.js
export default {
  modules: ['nuxt-security'],
  
  security: {
    headers: {
      // 安全相关 HTTP 头
      crossOriginResourcePolicy: 'same-origin',
      crossOriginOpenerPolicy: 'same-origin',
      crossOriginEmbedderPolicy: 'require-corp',
      contentSecurityPolicy: {
        'default-src': ["'self'"],
        'script-src': ["'self'", "'unsafe-inline'"],
        'style-src': ["'self'", "'unsafe-inline'"],
        'img-src': ["'self'", 'data:', 'https:']
      }
    }
  }
}

七、监控和分析

1. 集成 Google Analytics 4

javascript

javascript 复制代码
// plugins/analytics.client.js
export default defineNuxtPlugin((nuxtApp) => {
  const router = useRouter();
  
  window.dataLayer = window.dataLayer || [];
  function gtag() { dataLayer.push(arguments); }
  gtag('js', new Date());
  gtag('config', 'G-XXXXXXXXXX');
  
  // 跟踪页面视图
  router.afterEach((to) => {
    gtag('event', 'page_view', {
      page_title: document.title,
      page_location: window.location.href,
      page_path: to.path
    });
  });
});

2. 性能监控

vue

scss 复制代码
<script setup>
// 监控 Core Web Vitals
if (process.client) {
  import('web-vitals').then(({ getCLS, getFID, getLCP }) => {
    getCLS(console.log);
    getFID(console.log);
    getLCP(console.log);
    
    // 发送到分析服务
    const reportData = (metric) => {
      fetch('/api/web-vitals', {
        method: 'POST',
        body: JSON.stringify(metric),
        headers: { 'Content-Type': 'application/json' }
      });
    };
    
    getCLS(reportData);
    getFID(reportData);
    getLCP(reportData);
  });
}
</script>

八、实用工具和命令

1. SEO 检查脚本

javascript

javascript 复制代码
// scripts/check-seo.js
import { generateSiteMap } from './utils/sitemap.js';
import { checkMetaTags } from './utils/meta-checker.js';
import { analyzePerformance } from './utils/performance.js';

async function runSEOCheck() {
  console.log('开始 SEO 检查...');
  
  // 检查所有页面的 Meta 标签
  await checkMetaTags();
  
  // 生成并验证 sitemap
  await generateSiteMap();
  
  // 性能分析
  await analyzePerformance();
  
  console.log('SEO 检查完成!');
}

runSEOCheck();

2. 构建优化

json

json 复制代码
// package.json
{
  "scripts": {
    "build": "nuxt build --preset seo-optimized",
    "generate": "nuxt generate",
    "postbuild": "node scripts/analyze-bundle.js"
  }
}

九、常见问题解决

1. 处理动态路由 SEO

javascript

javascript 复制代码
// nuxt.config.js
export default {
  nitro: {
    prerender: {
      routes: async () => {
        const posts = await $fetch('/api/posts');
        return posts.map(post => `/blog/${post.slug}`);
      }
    }
  }
};

2. 处理无限滚动内容

vue

xml 复制代码
<script setup>
// 为无限滚动内容添加规范链接和分页标记
useHead({
  link: [
    { rel: 'canonical', href: `https://your-domain.com${route.path}` },
    { rel: 'next', href: `/page/${currentPage + 1}` },
    { rel: 'prev', href: `/page/${currentPage - 1}` }
  ],
  script: [
    {
      type: 'application/ld+json',
      innerHTML: JSON.stringify({
        '@context': 'https://schema.org',
        '@type': 'ItemList',
        'itemListElement': items.map((item, index) => ({
          '@type': 'ListItem',
          'position': index + 1,
          'url': `https://your-domain.com/item/${item.id}`
        }))
      })
    }
  ]
});
</script>

总结:Nuxt.js SEO 检查清单

  • 启用 SSR 或 SSG(根据需求选择)
  • 正确配置 nuxt.config.js 中的 SEO 选项
  • 每个页面都有唯一的 titlemeta description
  • 使用正确的 HTML 语义化标签(H1-H6)
  • 所有图片都有 alt 属性和合适尺寸
  • 配置 XML Sitemap 和 robots.txt
  • 添加结构化数据(JSON-LD)
  • 实施 Core Web Vitals 优化
  • 设置缓存策略和 HTTP 头
  • 添加分析跟踪代码
  • 多语言网站添加 hreflang
  • 定期检查死链和重定向
  • 移动端友好测试通过
  • 提交到 Google Search Console
相关推荐
wearegogog1235 小时前
基于 MATLAB 的卡尔曼滤波器实现,用于消除噪声并估算信号
前端·算法·matlab
Drawing stars5 小时前
JAVA后端 前端 大模型应用 学习路线
java·前端·学习
品克缤5 小时前
Element UI MessageBox 增加第三个按钮(DOM Hack 方案)
前端·javascript·vue.js
小二·5 小时前
Python Web 开发进阶实战:性能压测与调优 —— Locust + Prometheus + Grafana 构建高并发可观测系统
前端·python·prometheus
小沐°6 小时前
vue-设置不同环境的打包和运行
前端·javascript·vue.js
qq_419854056 小时前
CSS动效
前端·javascript·css
烛阴6 小时前
3D字体TextGeometry
前端·webgl·three.js
桜吹雪7 小时前
markstream-vue实战踩坑笔记
前端
C_心欲无痕7 小时前
nginx - 实现域名跳转的几种方式
运维·前端·nginx
花哥码天下7 小时前
恢复网站console.log的脚本
前端·javascript·vue.js