VUE+localStorages实现最近浏览

  • 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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值