美文网首页
Vue+localStorage历史搜索

Vue+localStorage历史搜索

作者: 若沫成海 | 来源:发表于2019-06-19 12:51 被阅读0次
 <div class="header-middle">
                <input 
                type="text" 
                class="header-input" 
                placeholder="输入城市或景点" 
                v-model="inputMsg"/>
  </div>
   <div class="header-right" @click="handleClickSeach">搜索</div>
export default {
    name:'TicketHeader',
    data:function(){
        return{
            inputMsg:'',
            historySearch:[]
        }
    },
    methods:{
       handleClickSeach(){
            if(this.inputMsg!==''){
                let storage=window.localStorage   
                if(storage.getItem('searchWord')==null){
                    this.historySearch.unshift({keyWord:this.inputMsg})
                    storage.setItem('searchWord',JSON.stringify(this.historySearch))
                }else{
                    if(!JSON.parse(storage.getItem('searchWord')).find(v => v.keyWord === this.inputMsg)){
                        if( this.historySearch.length >= 6){
                                this.historySearch.pop()                            
                            }
                            this.historySearch.unshift({keyWord:this.inputMsg})
                            storage.setItem('searchWord',JSON.stringify(this.historySearch))
                    }
                }
            }
    },
    created(){
        //获取localstorage
        let storage=window.localStorage
        if(storage.getItem('searchWord')!==null){
            this.historySearch=JSON.parse(storage.getItem('searchWord'))
        } 
    }
}

JSON.parse() 方法将字符串转换为 JavaScript 对象
JSON.stringify() 方法是将一个JavaScript值(对象或者数组)转换为一个 JSON字符串

相关文章

网友评论

      本文标题:Vue+localStorage历史搜索

      本文链接:https://www.haomeiwen.com/subject/zszfqctx.html