vue分類頁開發--axios數據獲取,localstorage數據緩存

来源:https://www.cnblogs.com/chenyingying0/archive/2020/04/07/12651154.html
-Advertisement-
Play Games

效果圖 1、首先在app.vue中,給路由添加keep-alive,使其能夠被緩存 2、配置路由 router/index.js 3、書寫各部分組件 src/pages/category/header.vue <template> <div class="header"> <i class="ico ...


效果圖

 

1、首先在app.vue中,給路由添加keep-alive,使其能夠被緩存

 

 

2、配置路由 router/index.js

 

 

3、書寫各部分組件

src/pages/category/header.vue

<template>
    <div class="header">
        <i class="iconfont icon-scan header-left"></i>
        <div class="header-center">搜索框</div>
        <i class="iconfont icon-msg header-right"></i>
    </div>
</template>

<script>
export default {
    name:'CategoryHeader'
}
</script>

<style lang="scss" scoped>
    .header{
        background-color:rgba(222, 24, 27, 0.9);
        transition:background-color 0.5s;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding:5px 20px;

        .iconfont{
            font-size:24px;
            color:#fff;
        }

        .header-center{
            flex:1;
        }
    } 
</style>

 

src/pages/category/tab.vue

<template>
    <div class="tab-container">
        <ul class="tab">
            <li class="tab-item" :class="{'tab-item-active':item.id===curId}" v-for="(item,index) in items" :key="index" @click="switchTab(item.id)">
                {{item.name}}
            </li>
        </ul>
    </div>
</template>

<script>
import {categoryNames} from './config';

export default {
    name:'CategoryTab',
    data(){
        return{
            items:categoryNames,
            curId:""
        }
    },
    created(){
        this.switchTab(this.items[0].id);
    },
    methods:{
        switchTab(id){
            this.curId=id;
            this.$emit("switch-tab",id);//派發事件,傳遞id
        }
    }
}
</script>

<style lang="scss" scoped>
    .tab-container{
        width:100%;
        height:100%;
        overflow:auto;
    }
  .tab {
    width: 100%;
    height:auto;

    &-item {
      height: 46px;
      background-color: #fff;
      border-right: 1px solid #e5e5e5;
      border-bottom: 1px solid #e5e5e5;
      color: #080808;
      font-size: 14px;
      font-weight: bold;
      text-align: center;
      line-height: 46px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

      &:last-child {
        border-bottom: none;
      }
    }

    &-item-active {
      background: none;
      border-right: none;
      color: #f23030;
    }
  }
</style>

 

src/pages/category/content.vue

<template>
<div class="content-wrapper">
    <div class="loading-container" v-if="isLoading">
      <div class="loading-wrapper">
        <me-loading/>
      </div>
    </div>
    <scrollbar ref="scroll" @pull-up="pullUp" @pull-down="pullRefresh">
      <div class="content">
        <div class="pic" v-if="content.banner">
          <a :href="content.banner.linkUrl" class="pic-link">
            <img @load="updateScroll" :src="content.banner.picUrl" class="pic-img">
          </a>
        </div>
        <div class="section" v-for="(section, index) in content.data" :key="index" >
          <h4 class="section-title">{{section.name}}</h4>
          <ul class="section-list">
            <li class="section-item" v-for="(item, i) in section.itemList" :key="i" >
              <a :href="item.linkUrl" class="section-link">
                <p class="section-pic" v-if="item.picUrl">
                  <img v-lazy="item.picUrl" class="section-img" />
                </p>
                <p class="section-name">{{item.name}}</p>
              </a>
            </li>
          </ul>
        </div>
      </div>
    </scrollbar>
    <div class="g-backtop-container">
        <me-backtop :visible="backtopVisible" @backtop="backtop" />
    </div>
  </div>
</template>

<script>
import {getCategorys} from 'api/category';
import MeLoading from 'components/loading';
import Scrollbar from 'components/scroll';
import MeBacktop from 'components/backtop';
import storage from 'assets/js/storage.js';
import {CATEGORY_CONTENT_KEY,CATEGORY_CONTENT_UPDATE_TIME} from './config';

export default {
    name:'CategoryContent',
    components:{
        MeLoading,
        Scrollbar,
        MeBacktop,
    },
    props:{
        curId:{
            type:String,
            default:''
        }
    },
    data(){
        return{
            content:{},
            isLoading:false,
            backtopVisible:false,
        }
    },
    watch:{
        curId(id){
            this.isLoading=true;
            this.getContent(id).then(()=>{
                this.isLoading=false;
                this.backtop();//回到頂部
            });
        }
    },
    methods:{
        getContent(id){
          let content=storage.get(CATEGORY_CONTENT_KEY);
          let updateTime;
          const curTime=new Date().getTime();

          if(content && content[id]){
            updateTime=content[id].updateTime||0;
            
            if(curTime-updateTime<CATEGORY_CONTENT_UPDATE_TIME){//未超時
              console.log('從緩存獲取');
              return this.getContentByStorage(content[id]);//從緩存獲取
            }else{
              console.log('從伺服器獲取');
              return this.getContentByHTTP(id).then(()=>{//從伺服器獲取
                this.updateStorage(content,id,updateTime);//更新緩存
              });
            }
          }else{
            console.log('從伺服器獲取');
            return this.getContentByHTTP(id).then(()=>{//從伺服器獲取
              this.updateStorage(content,id,curTime);//更新緩存
            });
          }           
        },
        getContentByStorage(content){
          this.content=content.data;
          return Promise.resolve();//返回一個成功的promise對象
        },
        getContentByHTTP(id){
          return getCategorys(id).then(data=>{
            return new Promise(resolve=>{
              if(data){
                this.content=data.content;
                resolve();
              }
            })              
          })
        },
        updateStorage(content,id,curTime){
          //content=content || {};
          content[id]={};
          content[id].data=this.content;
          content[id].updateTime=curTime;
          storage.set(CATEGORY_CONTENT_KEY,content);
        },
        updateScroll(){
            this.$refs.scroll && this.$refs.scroll.update();
        },
        scrollEnd(translate,swiper,pulling){//下拉刷新結束
            //顯示回到頂部按鈕
            this.backtopVisible=translate<0 && -translate>swiper.height;//向下拉並且距離大於一屏          
        },
        backtop(){
            this.$refs.scroll && this.$refs.scroll.scrollTop();//回到頂部
        },
        pullUp(end){
          end();
        },
        pullRefresh(end){
          this.getContent(this.curId).then(()=>{
                this.isLoading=false;
                this.backtop();//回到頂部
                end();
          });
        }
    }
}
</script>

<style lang="scss" scoped>
    .g-backtop-container{
        position: absolute;
        z-index:1100;
        right:10px;
        bottom:60px;
    }
 .content-wrapper {
    position: relative;
    height: 100%;
  }

  .loading-container {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1190;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: row;
    width: 100%;
    height: 100%;

    .mine-loading {
      color: #fff;
      font-size: 14px;
    }
  }
  .loading-wrapper {
    width: 50%;
    padding: 30px 0;
    background-color: rgba(0, 0, 0, 0.4);
    border-radius: 4px;
  }

  .content {
    padding: 10px;
  }

  .pic {
    margin-bottom: 12px;

    &-link {
      display: block;
    }

    &-img {
      width: 100%;
    }
  }

  .section {
    margin-bottom: 12px;

    &:last-child {
      margin-bottom: 0;
    }

    &-title {
      height: 28px;
      line-height: 28px;
      color: #080808;
      font-weight: bold;
    }

    &-list {
      display: flex;
      flex-wrap: wrap;
      background-color: #fff;
      padding: 10px 10px 0;
    }

    &-item {
      width: (100% / 3);
    }

    &-link {
      display: block;
    }

    &-pic {
      position: relative;
      width: 80%;
      padding-bottom: 80%;
      margin: 0 auto;
    }

    &-img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }

    &-name {
      height: 36px;
      line-height: 36px;
      text-align: center;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
  }
  .g-backtop-container {
    bottom: 10px;
  }
</style>

 

src/pages/category/index.vue

<template>
    <div class="category">
        <div class="g-header-container">
            <category-header />
        </div>
        <div class="g-content-container">
            <div class="sidebar">
                <category-tab @switch-tab="getCurId" />
            </div>
            <div class="main">
                <category-content :curId="curId" />
            </div>
        </div>
    </div>
</template>

<script>
import CategoryHeader from './header';
import CategoryTab from './tab';
import CategoryContent from './content';

export default {
    name:'Category',
    components:{
        CategoryHeader,
        CategoryTab,
        CategoryContent
    },
    data(){
        return{
            curId:''
        }
    },
    methods:{
        getCurId(id){
            this.curId=id;
        }
    }
}
</script>

<style lang="scss" scoped>
    html,body{
        width:100%;
        height:100%;
    }
    .category {
        overflow:hidden;
        width:100%;
        height:100%;
        background-color: '#f5f5f5';
    }

    .g-content-container {
        width:100%;
        height:100%;
        display: flex;
    }
    .sidebar {
        width: 80px;
        height: 100%;
    }
    .main {
        flex: 1;
        height: 100%;
    }
</style>

 

4、儲存常量和伺服器獲取來的數據

src/pages/category/config.js

export const CATEGORY_CONTENT_KEY='cyymall-category-content-key';
export const CATEGORY_CONTENT_UPDATE_TIME=1*24*60*60*1000;//1天

export const categoryNames = [
    {
      'name': '熱門推薦',
      'id': 'WQR2006'
    },
    {
      'name': '慕淘超市',
      'id': 'WQ1968'
    },
    {
      'name': '國際名牌',
      'id': 'WQ1969'
    },
    {
      'name': '奢侈品',
      'id': 'WQ1970'
    },
    {
      'name': '全球購',
      'id': 'WQ1971'
    },
    {
      'name': '男裝',
      'id': 'WQ1972'
    },
    {
      'name': '女裝',
      'id': 'WQ1973'
    },
    {
      'name': '男鞋',
      'id': 'WQ1974'
    },
    {
      'name': '女鞋',
      'id': 'WQ1975'
    },
    {
      'name': '內衣配飾',
      'id': 'WQ1976'
    },
    {
      'name': '箱包手袋',
      'id': 'WQ1977'
    },
    {
      'name': '美妝個護',
      'id': 'WQ1978'
    },
    {
      'name': '鐘錶珠寶',
      'id': 'WQ1979'
    },
    {
      'name': '手機數位',
      'id': 'WQ1980'
    },
    {
      'name': '電腦辦公',
      'id': 'WQ1981'
    },
    {
      'name': '家用電器',
      'id': 'WQ1982'
    },
    {
      'name': '食品生鮮',
      'id': 'WQ1983'
    },
    {
      'name': '酒水飲料',
      'id': 'WQ1984'
    },
    {
      'name': '母嬰童鞋',
      'id': 'WQ1985'
    },
    {
      'name': '玩具樂器',
      'id': 'WQ1986'
    },
    {
      'name': '醫葯保健',
      'id': 'WQ1987'
    },
    {
      'name': '計生情趣',
      'id': 'WQ1988'
    },
    {
      'name': '運動戶外',
      'id': 'WQ1989'
    },
    {
      'name': '汽車用品',
      'id': 'WQ1990'
    },
    {
      'name': '家居廚具',
      'id': 'WQ1991'
    },
    {
      'name': '傢具家裝',
      'id': 'WQ1992'
    },
    {
      'name': '禮品鮮花',
      'id': 'WQ1993'
    },
    {
      'name': '寵物生活',
      'id': 'WQ1994'
    },
    {
      'name': '生活旅行',
      'id': 'WQ1995'
    },
    {
      'name': '圖書音像',
      'id': 'WQ1996'
    },
    {
      'name': '郵幣',
      'id': 'WQ1997'
    },
    {
      'name': '農資綠植',
      'id': 'WQ1998'
    },
    {
      'name': '特產館',
      'id': 'WQ1999'
    },
    {
      'name': '慕淘金融',
      'id': 'WQ2000'
    },
    {
      'name': '拍賣',
      'id': 'WQ2001'
    },
    {
      'name': '房產',
      'id': 'WQ2008'
    },
    {
      'name': '二手商品',
      'id': 'WQ2002'
    }
  ];

 

5、axios獲取數據

src/api/category.js

import axios from 'axios';

// CancelToken:快速發送多個請求時,取消前面的請求,以最後一個為準
const CancelToken=axios.CancelToken;
let cancel;

//獲取數據 ajax
export const getCategorys=(id)=>{
    cancel && cancel("取消了前一次請求");
    cancel=null;

    let url='http://www.imooc.com/api/category/content/'+id;

    return axios.get(url,{
        cancelToken:new CancelToken(function executor(c){
            cancel=c;
        })
    }).then(res=>{
        
        if(res.data.code===0){
            console.log("獲取category成功");
            return res.data;
        }

        throw new Error('沒有成功獲取到數據');
    }).catch(err=>{
        console.log(err);
    });
}

 

6、localstorage操作緩存

const storage = window.localStorage;

export default {
  set(key, val) {
    if (val === undefined) {
      return;
    }
    storage.setItem(key, serialize(val));
  },
  get(key, def) {
    const val = deserialize(storage.getItem(key));
    return val === undefined ? def : val;
  },
  remove(key) {
    storage.removeItem(key);
  },
  clear() {
    storage.clear();
  }
};

function serialize(val) {
  return JSON.stringify(val);
}

function deserialize(val) {
  if (typeof val !== 'string') {
    return undefined;
  }
  try {
    return JSON.parse(val);
  } catch (e) {
    return val || undefined;
  }
}

 

最後補充一下,關於 $nextTick


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 10年前,我寫了第一個CLR存儲過程在SQL Server里,10年後,我又寫了一個。 我花了1個小時才找到如何創建CLR項目…… 創建C# CLR項目的地方變了,在VS 2010里有專門的項目模板: 但是在VS 2015里,只有先創建資料庫對象,然後添加SQL CLR C#類型的Item了: 之後 ...
  • 作為ETL的一部分,有時候就是需要把數據的Insert腳本生成出來,然後人肉拷貝到另一個地方執行。 熟悉SMSS的同學們都知道,有個生成腳本的任務,可以生成資料庫的create腳本啊什麼的,其實也能夠生產表中的數據。 自動化的ETL總不能連導出數據都人肉。。。一是容易出錯,二是太low了。 C#控制 ...
  • 曾多次聽到“MySQL為什麼選擇RR為預設隔離級別”的問題,其實這是個歷史遺留問題,當前以及解決,但是MySQL的各個版本沿用了原有習慣。歷史版本中的問題是什麼,本次就通過簡單的測試來說明一下。 1、 準備工作 1.1 部署主從 部署一套主從架構的集群,創建過程較簡單,可以參考歷史文章部署 MySQ ...
  • 字元函數,顧名思義,操作的就是字元串。通過下圖,我們來瞭解一下Oracle的字元函數。 一、大小寫控制函數 lower、upper、initcap select lower('Hello World') 轉小寫,upper('Hello World') 轉大寫,initcap('hello worl ...
  • 一、Oracle的Drop Table語句 首先,我們來看一下Oracle Drop Table的語法格式。 解釋一下裡面的參數: schema Schema表示方案名稱,這裡可以理解為用戶名,預設為當前用戶下的表。比如,要刪除scott用戶下的emp表,drop table scott.emp p ...
  • 前言: 之前有朋友加好友與我探討一些問題,我覺得這些問題倒挺有價值的;於是就想在本公眾號開設一個問答專欄,方便技術交流與分享,專欄名就定為: 《讀者來信》 。如遇到本人能力有限難以解決的問題,我將轉發該文至我的資源圈儘力尋求大佬們出手幫助,並附上提問者微信二維碼,希望給大家提供這樣一個互幫互助解決問 ...
  • redis 分散式緩存實戰-redis 事務 1.描述 redis 事務單獨的隔離操作:事務中的所有命令都會序列化、按順序執行。事務在執行過程中,不會被其他客戶端發送過來的命令請求所打斷。 redis 事務沒有隔離級別的概念:隊列中的命令沒有提交之前都不會實際的被執行,因為事務提交前任何指令都不會被 ...
  • 一、摘要 1.閱讀該篇,需要對runtime底層及類對象數據結構有一定瞭解,本篇僅著重講解方法緩存的演算法; 2.以下以類對象來論述,元類對象以此類推; 二、類對象數據結構 //rumtime源碼 //小碼哥圖片 說明:其中cache_t類型變數cache就是用來緩存曾經調度過的方法; 三、方法調度原 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...