在 Vue 3 中可用 computed 响应式截取搜索历史前 10 条:const displayedHistory = computed(() => searchHistory.value.slice(0, 10)),安全、简洁、自动更新;模板中直接遍历 displayedHistory 即可。

在 Vue 3 中,可以用 computed 基于原始搜索历史数组,返回截取后的前 10 条记录,既响应式又简洁。
定义原始搜索历史数据
通常搜索历史存在 ref 或 reactive 中,比如:
const searchHistory = ref(['Vue 3', 'computed', 'ref', 'pinia', /* ... 更多条 */])
用 computed 截取前 10 条
直接在 setup 中声明计算属性,调用 .slice(0, 10) 即可:
const displayedHistory = computed(() => searchHistory.value.slice(0, 10))
-
slice(0, 10)安全:若原数组不足 10 条,自动返回全部,不会报错 - 响应式更新:只要
searchHistory.value变化,displayedHistory自动重新计算 - 无需手动 watch 或 onUpdated,符合 Composition API 的声明式逻辑
模板中直接使用
在模板里遍历 displayedHistory 即可:
- {{ item }}
- 避免在模板中写
searchHistory.slice(0,10)—— 会失去响应性,且每次渲染都新建数组,不推荐 - 如需带删除、清空等操作,仍操作
searchHistory原数组,computed会自动同步更新视图
进阶:按时间倒序 + 去重再截取(可选)
如果历史是对象数组(含时间戳),或需要去重,可在 computed 内组合处理:
const displayedHistory = computed(() => {
return [...new Set(searchHistory.value)] // 去重(字符串数组)
.slice(-10) // 取最后 10 条(即最新)
.reverse() // 恢复正序展示(最新在上)
})注意:确保 searchHistory.value 类型一致,避免 slice 在 null/undefined 上报错,必要时加空值保护:
const displayedHistory = computed(() =>
Array.isArray(searchHistory.value)
? searchHistory.value.slice(0, 10)
: []
)前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










