VUE+localStorages实现最近访问页面

50 阅读1分钟

显示最近访问入口页面:

<h4>最近访问</h4>
      <div class="list_title">
        <div class="list_item" v-for="item in recentlyVisited" :key="item.name" @click="jump(item)">
          <i class="el-icon-document title"></i>
          <span  style="font-size: 14px;">{{ item.title }}</span>
        </div>
import {delVisit, getRecentlyVisited,addVisit} from "./components/home.js";

created() {
    this.recentlyVisited = getRecentlyVisited()
  },
 methods: {
    del(row) {
      delVisit(row)
      this.recentlyVisited = getRecentlyVisited()
    },
    jump(row){
      this.$router.push({
        path:row.name,
      })
    }
  },

在需要被记录的页面中添加:

  created() {
    addVisit({ name: 'path', title: 'xx' })
  },

home.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
  }

原文链接:blog.csdn.net/gacellk/art…