當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JS设置页面缓存
這里講一下,JS如何設置頁面緩存?
第一種:vue設置頁面切換緩存
效果如下:
相互切換頁面的時候,如果存在緩存,則使用緩存里面的數據。
項目結構:
代碼部分
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><!-- 子組件,顯示不同的 tabis 特性動態綁定子組件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緩存
這里就直接講一下原理:
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")));總結
- 上一篇: cf枪王排位点开始匹配没反应的原因 三亿
- 下一篇: 百度贴吧app登录不了(登录百度帐号)