使用localstrage实现历史记录操作

2019-01-22  本文已影响6人  sweetBoy_9126

需要实现的功能:

当我们什么都没点击的时候,不会显示任何东西,而当我们点击一个内容的时候再返回下方就会显示你点击过的内容,你再次点击它就会直接回到对应的页面,还可以对它进行删除

思路:一开始判断页面中如果没有对应的loaclstrage存在的话就去新建一个,利用一个数组来存取它的值,因为localstrage只能存字符串,所以需要使用JSON.stringfy把你数组的内容转成json格式的字符串,然后让当前这个数组等于你通过JSON.parse转译的localstrage的值,之后每次点击的时候都需要把当前数据push到数组中,然后,重新建一个同名的localstrage再次将数组赋值给它,每次渲染的时候只需要对数组进行渲染就行,删除的时候也一样先删除数组中对应的元素,然后再次新建一个同名localstrage,将数组赋值给它

let model = {
  data: {
    historyList: []
  },
  updataHistoryList(){
    console.log(this.data.historyList)
    localStorage.setItem('search-history',JSON.stringify(this.data.historyList))
},
}
let controller = {
  hotSearch(){
    this.$el.find('.hot').on('click','li',(e)=>{
        this.$el.find('.search-start').addClass('hidden')
        let a = $(e.currentTarget).find('a')
        let text = a.text()
        let href = a.attr('href')
        this.updataHistoryList({name:text,href})
        this.model.updataHistoryList()
        console.log(localStorage.getItem('search-history'))
    })
},
  //初始化
historyListInit(){
    this.historyListData = this.model.data.historyList
    if(!localStorage.getItem('search-history')){
        this.model.updataHistoryList()
    }
    this.$data.historyList = JSON.parse(localStorage.getItem('search-history'))
    this.view.renderHistory(this.$data.historyList)
},
updataHistoryList(data){
    this.$data.historyList.push(data)
    this.noRepeat(this.$data.historyList,'historyList')
    this.view.renderHistory(this.$data.historyList)
},
deleteHistory(){
    this.$el.find('.history-list').on('click','.delete',(e)=>{
        let current = $(e.currentTarget).parent().find('a').text()
        for(let i =0;i<this.$data.historyList.length;i++){
            if(this.$data.historyList[i].name === current){
                this.$data.historyList.splice(i,1)
                this.view.renderHistory(this.$data.historyList)
                this.model.updataHistoryList()
                break
            }
        }
    })
}
}

上一篇 下一篇

猜你喜欢

热点阅读