vue中常用的优化
文章类型:Vue
发布者:hp
发布时间:2023-05-20
在实际开发过程中,经常会对代码进行优化,提高渲染性能
v-if彻底销毁组件,而v-show使用display,只是隐藏,
不要使用index作为key,在某些情况下回导致重复渲染
减少不必要的计算和重复渲染,只有当依赖发生变化才重新计算
// Vue组件
export default {
data() {
return {
items: [1, 2, 3, 4, 5],
};
},
computed: {
// 计算属性,返回 items 数组的总和
total() {
console.log('计算总和');
return this.items.reduce((sum, num) => sum + num, 0);
},
},
};
频繁切换的组件 tabs会增加渲染,合理使用缓存组件方法,避免在组件切换时进行重复的创建和销毁操作,从而提高性能和响应速度
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>针对体积较大的组件,拆包,需要时异步加载,不需要时不加载,减少主包体积,首页会加载更快
<!-- index.vue -->
<template>
<Child></Child>
</template>
<script>
import { defineAsyncComponent } from 'vue'
export default {
name: 'AsyncComponent',
components: {
// child体积大 异步加载才有意义
// defineAsyncComponent vue3的写法
Child: defineAsyncComponent(() => import(/* webpackChunkName: "async-child" */ './Child.vue'))
}
}
</>
<!-- child.vue -->
<template>
<p>async component child</p>
</template>
<script>
export default {
name: 'Child',
}
</script>六:路由懒加载
保证首页先加载,其他路由进行拆分,动态加载
const routes = [
{
path: '/',
name: 'Home',
component: Home // 直接加载
},
{
path: '/about',
name: 'About',
// 路由懒加载
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]使用三方库Nuxt.js按需优化,部分在服务器端渲染,提供更好的SEO、性能和用户体验,同时开发和部署的复杂性以及服务器资源的消耗增大
暂无评论,快来发表第一条评论吧~