vue 数据缓存和懒加载

vue 数据缓存和懒加载

1.有些时候,不希望已经请求过的数据,再次请求,重复执行刷新操作,我们就需要使用数据缓存,

一、第一种方式,也是通用的思路,利用一个空数组,或者直接以存在Session Storage,这种页面级缓存,需要

页面没有被销毁,每次请求前先查看用于存储的数据中是否有数据,没有再发起请求,具体实现代码如下:

// 缓存对象,用于缓存查询到的商品列表数据ProductList
	// key: 使用 categoryId
	// value: 使用根据 categoryId 查询到的 productList 值
	const cache = {}

	// 页面级数据缓存
	export default {
		name: "CategoryList",
		data() {
			return {
				productList: []
			}
		},
		methods: {
			// 查询数据
			getCategoryListData(categoryId) {
				// 判断是否在缓存中保存待请求 categoryId 对应的数据
				if (Object.keys(cache).includes(categoryId)) { // 缓存中存在,则直接使用
					this.productList = cache[categoryId]
				} else { // 缓存中不存在,则ajax请求
					// 发起ajax请求(笔者已将请求定义到全局,主要观看思路)
					this.$http.getProductList(categoryId)
							.then(res => {
								this.productList = res.list
								// 请求到的数据加入缓存
								cache[categoryId] = res.list
							})
				}
			},

二,使用vue自带的缓存keep-alive(组件)

keep-alive是Vue提供的一个抽象组件,用来对组件进行缓存,从而节省性能,由于是一个抽象组件,所以在v页面渲染完毕后不会被渲染成一个DOM元素

当组件在 <keep-alive> 内被切换,它的 activateddeactivated 这两个生命周期钩子函数将会被对应执行。 同时,页面也会失去2个钩子函数 created 和mounted

使用<keep-alive>会将数据保留在内存中,如果要在每次进入页面的时候获取最新的数据,需要在activated阶段获取数据,承担原来created钩子中获取数据的任务。 这也表示被组件包裹的的组件将不会重新渲染,所以需要我们在特定的情况下强制刷新某些组件

利用include、exclude属性

<keep-alive include="bookLists,bookLists">
      <component>
  </component>
</keep-alive>
<keep-alive exclude="indexLists">
      <component>
  </component>
</keep-alive>

include属性表示只有name属性为bookLists,bookLists的组件会被缓存,(注意是组件的名字,不是路由的名字)其它组件不会被缓存exclude属性表示除了name属性为indexLists的组件不会被缓存,其它组件都会被缓存,(值也可以可以用逗号分隔字符串、正则表达式或一个数组 )

当然有人会想,这个name改写在哪? 这个值就是定义组件时的name选项

// 组件 "bookLists"
export default {
  name: 'bookLists',
  data () {
    return {}
  }
}

2.5版后新增加max属性

最多可以缓存多少组件实例。一旦这个数字达到了,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉。

<keep-alive :max="10">
  <component ></component>
</keep-alive>

vue-router 利用meta属性实现缓存

router-view 也是一个组件,如果直接被包在 keep-alive 里面,所有路径匹配到的视图组件都会被缓存:

//在路由中定义,通过meta定义该页面是否需要缓存
export default[
 {
  path:'/',
  name:'home',
  components:Home,
  meta:{
    keepAlive:true //需要被缓存的组件
 },
 {
  path:'/book',
  name:'book',
  components:Book,
  meta:{
     keepAlive:false //不需要被缓存的组件
 } 
]
<keep-alivev v-if="this.$route.meat.keepAlive">
  <router-view ></router-view>
  <!--这里是会被缓存的组件-->
</keep-alive>
<keep-alive  v-if="!this.$router.meta.keepAlive">
  <router-view ><router-view  />
</keep-alive>
<!--这里是不会被缓存的组件-->

路由懒加载

在routes.js 将import Home from “/user/index”

改成cosnt Home =()=>import("/user/index")//这样就能实现路由分片打包,按需加载

import Vue from 'vue'
import Router from 'vue-router'
 cosnt  Home =()=>import("/user/index")
export default new Router({
    routes: [
        //第一种方式
        {
           path:'/',
          name:'home',
          components:Home,  
        },
        //第二种方式
       {
          path: '/login',
           component: () =>{
               import('@/views/login/index'),
           }
        },
    ]
        
    }
})
发布了52 篇原创文章 · 获赞 82 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/marendu/article/details/92769189
今日推荐