JS设置页面缓存

这里讲一下,JS如何设置页面缓存?

第一种:vue设置页面切换缓存

效果如下:
JS设置页面缓存
JS设置页面缓存
JS设置页面缓存

相互切换页面的时候,如果存在缓存,则使用缓存里面的数据。


项目结构:

JS设置页面缓存


代码部分

index.vue

<template>
  <div class="index">
    <div class="tabs">
      <div class="tab"
           @click="toggleTab('One')"><a>小王子</a></div>
      <div class="tab"
           @click="toggleTab('Two')"><a>小玫瑰</a></div>
      <div class="tab"
           @click="toggleTab('Three')"><a>小狐狸</a></div>
    </div>
    <!-- 子组件,显示不同的 tab
    is 特性动态绑定子组件
    keep-alive 将切换出去的组件保留在内存中 -->
    <div class="showTabs">
      <One :is="currentTab"
           keep-alive></One>
    </div>

  </div>
</template>

<script>
import One from './one'
import Two from './two'
import Three from './three'
export default {
  name: 'Cache',
  data () {
    return {
      currentTab: 'One'
    }
  },
  components: {
    One,
    Two,
    Three
  },
  methods: {
    toggleTab: function (tab) {
      this.currentTab = tab // tab 为当前触发标签页的组件名
    }
  }

}
</script>

<style lang="less" scope>
.tabs {
  display: flex;
  justify-content: center;
  .tab {
    padding: 10px 20px;
    border: 1px solid #999;
    background: aliceblue;
    margin: 10px 5px;
    border-radius: 10px;
  }
}
.showTabs {
  text-align: center;
  font-size: 16px;
  font-weight: 600;
  margin: 10px;
}
</style>

one.vue


<template>
  <div class="one">
    <div class="name">小王子</div>
    <div>
      <img src="http://img2.imgtn.bdimg.com/it/u=2218388696,3770858086&fm=26&gp=0.jpg"
           alt="" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'One',
  data () {
    return {

    }
  }

}
</script>

<style lang="less" scope>
.one img {
  width: 100%;
}
.name {
  margin-bottom: 15px;
}
</style>


two.vue


<template>
  <div class="two">
    <div class="name">小玫瑰</div>
    <div>
      <img src="http://img5.imgtn.bdimg.com/it/u=40547454,1744657715&fm=26&gp=0.jpg"
           alt="" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'Two',
  data () {
    return {

    }
  }

}
</script>

<style lang="less" scope>
.two img {
  width: 100%;
}
.name {
  margin-bottom: 15px;
}
</style>

three.vue


<template>
  <div class="three">
    <div class="name">小狐狸</div>
    <div>
      <img src="http://img0.imgtn.bdimg.com/it/u=3948950062,3962647218&fm=26&gp=0.jpg"
           alt="" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'Three',
  data () {
    return {

    }
  }

}
</script>

<style lang="less" scope>
.three img {
  width: 100%;
}
.name {
  margin-bottom: 15px;
}
</style>

第一种:使用localStorage缓存

这里就直接讲一下原理:

  1. 在接口请求时,将数据缓存在localstorage里面;
  2. 根据条件判断localstorage中是否存在需要的数据,如果有,直接拿,否则请求接口;

JSON 存储数组或者对象

到这里的话,我们一定会向localStorage 存储数组或者对象,这里讲一下存储对象

var obj = {"a": 1,"b": 2};
 localStorage.setItem("temp2", JSON.stringify(obj));//返回{"a":1,"b":2}
console.log(JSON.parse(localStorage.getItem("temp2")));