当前位置: 移动技术网 > IT编程>开发语言>JavaScript > vue分类页开发--axios数据获取,localstorage数据缓存

vue分类页开发--axios数据获取,localstorage数据缓存

2020年04月07日  | 移动技术网IT编程  | 我要评论

效果图

 

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网