- View.vue
<template> <div> <h3>最近浏览</h3> <el-table :data="recentlyVisited" style="width: 45vw;height: 35vh;margin-left: 1.2vw"> <el-table-column label="页面名称"> <template slot-scope="scope"> <a @click="jump(scope.row)">{{ scope.row.title }}</a> </template> </el-table-column> <el-table-column prop="time" label="最后浏览时间"></el-table-column> <el-table-column prop="todo"> <template slot-scope="scope"> <el-button type="text" @click="del(scope.row)">删除</el-button> </template> </el-table-column> </el-table> </div> </template> <script> import {delVisit, getRecentlyVisited} from "@/api/abu-omnc/homepage/homepage"; export default { name: 'RecentVisits', data() { return { recentlyVisited: [] } }, created() { this.recentlyVisited = getRecentlyVisited() }, methods: { del(row) { delVisit(row) this.recentlyVisited = getRecentlyVisited() }, jump(row){ this.$router.push({ path:row.name, }) } }, } </script>
- homepage.js
function getRecentlyVisited() { const visits = JSON.parse(localStorage.getItem('recentVisits')) || [] return visits.map((item) => { return { title: item.title, name: item.name, time: item.time } }).slice(0, 5) } function addVisit(item) { const visits = JSON.parse(localStorage.getItem('recentVisits')) || [] let index = visits.findIndex((v) => v.name === item.name) if (index >= 0) { // 如果已经存在,就更新时间戳 visits.splice(index, 1) } let date = new Date(); let time = date.getFullYear()+"/"+(date.getMonth()+1)+"/"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds() visits.unshift({ title: item.title, name: item.name, time: time}) localStorage.setItem('recentVisits', JSON.stringify(visits.slice(0, 10))) //addVisit({ name: 'page-name', title: 'Page Title' }) } function delVisit(item) { const visits = JSON.parse(localStorage.getItem('recentVisits')) || [] let index = visits.findIndex((v) => v.name === item.name) if (index >= 0) { // 如果已经存在,就删除 visits.splice(index,1) } localStorage.setItem('recentVisits', JSON.stringify(visits.slice(0, 10))) getRecentlyVisited(); } export { addVisit, getRecentlyVisited, delVisit }
- 在需要被最近浏览页面文件中的created方法中添加
addVisit({name: '页面路径', title: '页面名称'})
例如:
<template>
<h4>hello world</h4>
</template>
<script>
export default {created() { addVisit({name: '/helloworld', title: '世界你好'}) },}
</script>