1. localStorage //主
    2. sessionStorage

    区别:待补充…

    1. mounted() {
    2. var list = localStorage.getItem("list");
    3. if (list) {
    4. this.list = JSON.parse(list);
    5. } else {
    6. localStorage.setItem("list", "[]");
    7. }
    8. },
    9. updated() {
    10. localStorage.setItem("list", JSON.stringify(this.list));
    11. }
    1. //1.设置缓存
    2. sessionStorage.setItem
    3. <input type="text" v-model="keyword" @keyup="handleEnter">
    4. methods:{
    5. handleEnter(){
    6. sessionStorage.setItem("keyword",this.keyword)
    7. }
    8. },
    9. //2.获取缓存
    10. sessionStorage.getItem
    11. mounted(){
    12. var keyword=sessionStorage.getItem("keyword");
    13. if(keyword){
    14. this.keyword=keyword
    15. }
    16. }
    17. //如果要永久保存则需要用到localStorage,主要不清楚永久存在,将sessionStorage换掉
    1. //使用localStorage+watch
    2. <template>
    3. <div class="home">
    4. <input type="text" v-model="keyword" @keyup.enter="handleEnter" />
    5. <div v-for="item of arr" :key="item.word">
    6. <input type="checkbox" v-model="item.checked" />
    7. {{item.word}}
    8. </div>
    9. </div>
    10. </template>
    11. <script>
    12. export default {
    13. name: 'home',
    14. data(){
    15. return{
    16. keyword:"",
    17. arr:[],
    18. checked:false
    19. }
    20. },
    21. methods:{
    22. handleEnter(){
    23. this.arr.push({word:this.keyword,checked:false})
    24. /* localStorage值只能是字符串 JSON.stringify JSON.parse */
    25. var words=JSON.parse(localStorage.getItem("words"));
    26. words.push({"word":this.keyword,"checked":false});
    27. localStorage.setItem("words",JSON.stringify(words))
    28. }
    29. },
    30. mounted(){
    31. let words=localStorage.getItem("words");
    32. if(words){
    33. this.arr=JSON.parse(words);
    34. }else{
    35. localStorage.setItem("words","[]")
    36. }
    37. },
    38. watch:{
    39. arr:{
    40. handler(newVal){
    41. var words=JSON.parse(localStorage.getItem("words"));
    42. words=newVal;
    43. localStorage.setItem("words",JSON.stringify(words))
    44. },
    45. deep:true
    46. }
    47. }
    48. }
    49. </script>

    设置缓存

    1. public defaultCity:string = "武汉"
    2. changeCity(value:string){
    3. this.defaultCity = value;
    4. localStorage.setItem("city",value)
    5. }

    获取缓存

    1. getCity(){
    2. if(localStorage.getItem("city")){
    3. this.defaultCity = localStorage.getItem("city")
    4. }
    5. return this.defaultCity
    6. }

    生命周期调用缓存

    1. ngOnInit() {
    2. this.common.getCity()
    3. }