localStorage //主
sessionStorage
区别:待补充…
mounted() {
var list = localStorage.getItem("list");
if (list) {
this.list = JSON.parse(list);
} else {
localStorage.setItem("list", "[]");
}
},
updated() {
localStorage.setItem("list", JSON.stringify(this.list));
}
//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>
设置缓存
public defaultCity:string = "武汉"
changeCity(value:string){
this.defaultCity = value;
localStorage.setItem("city",value)
}
获取缓存
getCity(){
if(localStorage.getItem("city")){
this.defaultCity = localStorage.getItem("city")
}
return this.defaultCity
}
生命周期调用缓存
ngOnInit() {
this.common.getCity()
}