Nuxt 3实现文本折叠:兼顾Googlebot抓取与用户端展示
在Nuxt 3中实现SEO友好的长文本折叠功能
要实现默认显示3行描述文本、点击按钮展开全部,同时保证Googlebot能完整抓取所有内容的功能,核心思路是让完整文本直接存在于DOM中,仅通过CSS控制视觉显示状态,避免用JS动态移除或隐藏内容,确保搜索引擎能读取全部文本。
1. 创建可折叠描述组件
新建components/CollapsibleDescription.vue组件:
<template> <div class="collapsible-description"> <div :class="['description-content', { expanded: isExpanded }]"> {{ description }} </div> <button @click="toggleExpand" class="toggle-btn"> {{ isExpanded ? '收起' : '显示更多' }} </button> </div> </template> <script setup> const props = defineProps({ description: { type: String, required: true } }) const isExpanded = ref(false) const toggleExpand = () => { isExpanded.value = !isExpanded.value } </script> <style scoped> .collapsible-description { margin: 1rem 0; } .description-content { font-size: 1rem; line-height: 1.5; transition: max-height 0.3s ease; } /* 折叠状态:仅显示3行 */ .description-content:not(.expanded) { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; max-height: calc(1.5rem * 3); /* 行高 × 行数,确保高度匹配 */ } /* 展开状态:显示全部内容 */ .description-content.expanded { max-height: none; } .toggle-btn { margin-top: 0.5rem; border: none; background: transparent; color: #0071e3; cursor: pointer; font-size: 0.9rem; } .toggle-btn:hover { text-decoration: underline; } </style>
2. 在页面中使用组件
在需要展示长描述的页面(比如剧集详情页)引入组件:
<template> <div class="page-container"> <h1>剧集名称</h1> <CollapsibleDescription :description="seriesDescription" /> </div> </template> <script setup> const seriesDescription = `这里是你的长描述文本,所有内容会直接渲染到DOM中,Googlebot可以完整抓取全部内容。用户打开页面时默认只看到3行,点击"显示更多"按钮就能展开查看完整内容,再次点击则收起恢复折叠状态。` </script>
为什么这个方案对SEO友好?
- 所有文本直接输出到DOM结构中,没有通过AJAX动态加载或用
display: none隐藏,Googlebot可以完整解析全部内容 - 使用CSS的
line-clamp属性实现折叠,仅控制视觉显示效果,不影响内容的可访问性和搜索引擎抓取
内容的提问来源于stack exchange,提问作者Николай Андреевич
相关产品推荐
相关产品推荐

