vue 记录浏览历史存在记录不断返回 组件
时间: 2023-08-28 07:04:49 浏览: 52
实现浏览历史记录的方式有很多,以下是一种基于 Vue.js 的实现方式:
1. 定义一个数组 history 来存储浏览历史记录,每个记录包含一个标题和一个链接。
2. 在组件的 mounted 钩子函数中,将当前页面的标题和链接添加到 history 数组中。
3. 在模板中使用 v-for 指令遍历 history 数组,生成一个列表展示历史记录。
4. 为每个历史记录添加一个点击事件,在点击时调用一个方法,该方法接收一个参数 index,表示要返回到的历史记录的索引。
5. 在该方法中,通过 $router.push() 方法将页面导航到指定的历史记录的链接,同时将该历史记录之后的所有记录从 history 数组中删除。
以下是一个基本实现的代码示例:
```html
<template>
<div>
<h2>浏览历史</h2>
<ul>
<li v-for="(item, index) in history" :key="index" @click="goBack(index)">
{{ item.title }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
history: [],
};
},
mounted() {
this.history.push({
title: document.title,
link: this.$route.fullPath,
});
},
methods: {
goBack(index) {
const link = this.history[index].link;
this.history.splice(index + 1);
this.$router.push(link);
},
},
};
</script>
```
在以上代码中,我们通过监听 mounted 钩子函数来将页面的标题和链接添加到 history 数组中。在模板中使用 v-for 指令来遍历 history 数组,生成历史记录列表。在每个历史记录中添加一个点击事件,调用 goBack 方法来返回到指定的历史记录。在 goBack 方法中,我们通过 $router.push() 方法将页面导航到指定的历史记录的链接,并将该历史记录之后的所有记录从 history 数组中删除。