localStorage
sessionStorage
//1.设置缓存
sessionStorage.setItem
<input type="text" v-model="keyword" @keyup="handleEnter">
methods:{
handleEnter(){
sessionStorage.setItem("keyword",this.keyword)
}
},
//2.获取缓存
sessionStorage.getItem
mounted(){
var keyword=sessionStorage.getItem("keyword");
if(keyword){
this.keyword=keyword
}
}
//如果要永久保存则需要用到localStorage,只要不清除永久存在,将sessionStorage换掉
//使用localStorage+watch
<template>
<div class="home">
<input type="text" v-model="keyword" @keyup.enter="handleEnter" />
<div v-for="item of arr" :key="item.word">
<input type="checkbox" v-model="item.checked" />
{{item.word}}
</div>
</div>
</template>
<script>
export default {
name: 'home',
data(){
return{
keyword:"",
arr:[],
checked:false
}
},
methods:{
handleEnter(){
this.arr.push({word:this.keyword,checked:false})
/* localStorage值只能是字符串 JSON.stringify JSON.parse */
var words=JSON.parse(localStorage.getItem("words"));
words.push({"word":this.keyword,"checked":false});
localStorage.setItem("words",JSON.stringify(words))
}
},
mounted(){
let words=localStorage.getItem("words");
if(words){
this.arr=JSON.parse(words);
}else{
localStorage.setItem("words","[]")
}
},
watch:{
arr:{
handler(newVal){
var words=JSON.parse(localStorage.getItem("words"));
words=newVal;
localStorage.setItem("words",JSON.stringify(words))
},
deep:true
}
}
}
</script>