10 个 Vue.js 优化技巧

VueJS11个月前更新 admin
2,436 0

优化 Vue.js 应用程序性能是每个前端开发人员都关心的问题。

在本文中,我将分享初学者或中级前端需要了解的 10 个 Vue.js 优化技巧。 无论您是正在学习 Vue.js 还是已经在应用程序开发中使用它,我希望这些技巧对您有所帮助。

1.在v-for中设置key

文档链接:https://vuejs.org/api/built-in-directives.html#v-for

在 v-for 中使用 key 非常重要,因为它可以让 Vue 更好地跟踪每个元素的状态和位置。

当元素的顺序发生变化时,没有键会导致性能下降,因为 Vue 需要重新生成元素。 为了优雅地设置键,您可以从数据中提取一个唯一的属性作为键值。 这是示例代码:

<template v-for=“(item, index) in items” :key=“item.id”>
<div>{{ item.title }}</div>
</template>

如果没有像 item.id 这样的唯一属性,可以考虑使用 index 作为键值。

需要注意的是,当需要增删数据时,不要使用索引作为键值,否则可能会导致页面数据异常。

2.适当使用v-if和v-show

文档链接:https://vuejs.org/guide/essentials/conditional.html#v-if-vs-v-show

v-if和v-show都可以控制元素的显示和隐藏,只是使用场景不同。

v-if 适用于需要频繁切换的场景,组件内的事件监听器和子组件销毁重建;
v-show用于不需要频繁切换的场景,不考虑初始条件进行渲染,只是控制元素的CSS display属性控制是否显示;

总体而言,v-if 的切换开销较高,而 v-show 的初始渲染开销较高。 因此,如果需要频繁切换,则首选v-show; 如果绑定条件在运行时很少改变,则 v-if 更合适。 这是示例代码:

<!– Use v-if –>
<template v-if=“show”>
<div>{{ message }}</div>
</template>

<!– Use v-show –>
<template>
<div v-show=“show”>{{ message }}</div>
</template>

3、酌情使用KeepAlive缓存组件状态

文档链接:https://vuejs.org/guide/built-ins/keep-alive.html#keepalive

KeepAlive 是一个内置的组件,可以缓存组件的状态,避免重复渲染,提高页面响应速度。 在多个组件之间动态切换时缓存删除的组件实例。

但是,如果KeepAlive使用不当,可能会导致内存泄漏等问题。 因此,在使用KeepAlive时,需要了解其使用场景,及时销毁缓存的组件。 这是示例代码:

<template>
<keep-alive>
<router-view v-if=“$route.meta.keepAlive”></router-view>
</keep-alive>
</template>

另外KeepAlive还支持配置最大缓存实例数来限制最大可以缓存的组件实例数。 如果缓存实例的数量即将超过指定的最大数量,则最长时间未访问的缓存实例将被销毁,以便为新实例腾出空间。

这是示例代码:

<KeepAlive :max=“10”>
<component :is=“activeComponent” />
</KeepAlive>

4.及时销毁事件

文档链接:https://vuejs.org/api/composition-api-lifecycle.html#onbeforeunmount

使用事件监听器、定时器和异步操作的组件需要及时销毁,以防止内存泄漏。

Vue3中提供了setup函数,可以使用onBeforeUnmount hook销毁事件等资源。 这是示例代码:

import { onBeforeUnmount } from “vue”;
export default {
setup() {
let timer;
const startTimer = () => {
timer = setInterval(() => {
console.log(“timer is running”);
}, 1000);
};
const stopTimer = () => {
clearInterval(timer);
};
onBeforeUnmount(() => {
stopTimer();
});
return {
startTimer,
stopTimer,
};
},
};

5.注意音量优化

Vue3 比较大,需要针对尺寸进行优化。 这可以通过配置打包工具只打包需要的模块、按需引入第三方库等方式实现。

或者,您可以使用基于 Tree Shaking 的优化工具,如 PurgeCSS、Babel Minify 和 UglifyJS 来进一步压缩代码。 这是示例代码:

// vue.config.js
module.exports = {
configureWebpack: {
optimization: {
splitChunks: {
chunks: “all”,
minSize: 20000,
maxSize: 0,
minChunks: 1,
maxAsyncRequests: 30,
maxInitialRequests: 30,
automaticNameDelimiter: “~”,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true,
},
},
},
},
},
};

6.使用EventBus进行业务解耦

EventBus 使组件之间能够通信并使它们彼此解耦。 你也可以使用 Vuex 等全局状态管理工具来实现这一点。

使用EventBus时需要注意事件名称的命名,尽量避免多个组件监听同一个事件。 这是示例代码:

// event-bus.js
import mitt from “mitt”;
export const eventBus = mitt();
// component.js
export default {
mounted() {
eventBus.on(“foo”, this.handleFoo);
},
methods: {
handleFoo() {
// do something
},
},
beforeUnmount() {
eventBus.off(“foo”, this.handleFoo);
},
};
// other-component.js
export default {
mouted() {
eventBus.emit(“foo”);
},
};

7.使用动态组件解决if-else重载问题

当if-else逻辑过于复杂时,可以使用动态组件来实现,避免代码臃肿和可读性下降。 使用动态组件可以使代码组织得更清晰,组件重用,避免代码冗余。 这是示例代码:

<template>
<component :is=“componentName”></component>
</template>
<script>
import Foo from “./Foo.vue”;
import Bar from “./Bar.vue”;
export default {
data() {
return {
componentName: “”,
};
},
mounted() {
if (condition) {
this.componentName = “Foo”;
} else {
this.componentName = “Bar”;
}
},
components: {
Foo,
Bar,
},
};
</script>

8.用异步组件延迟加载

文档链接:https://vuejs.org/guide/components/async.html#async-components

异步组件可以实现延迟加载,减少组件加载时间,提高页面响应能力。 Vue3 原生支持异步组件加载,可以使用 import() 语法实现。 代码示例如下:

import { defineAsyncComponent } from “vue”;
const AsyncComp = defineAsyncComponent(() => import(“./Foo.vue”));

9. 使用 computed 和 watch 减少计算量

文档链接:https://vuejs.org/api/reactivity-core.html

使用 computed 和 watch 可以减少冗余渲染或重复计算。

computed可以缓存计算的结果,这样当响应式数据发生变化时,只有依赖的数据在发生变化时才重新计算。 watch可以监听一个或多个响应式数据源的变化并执行相应的动作,避免手动监听数据变化。

以下是示例代码:

<template>
<div>{{ fullName }}</div>
</template>
<script>
export default {
data() {
return {
firstName: “John”,
lastName: “Doe”,
};
},
computed: {
fullName() {
return this.firstName + ” ” + this.lastName;
},
},
watch: {
firstName(newValue, oldValue) {
console.log(“firstName”, newValue, oldValue);
},
lastName(newValue, oldValue) {
console.log(“lastName”, newValue, oldValue);
},
},
};
</script>

10. 使用 v-slot 优化作用域槽

文档链接:https://vuejs.org/api/built-in-directives.html#v-slot

范围槽(也称为命名槽)可以将数据从父组件传递到子组件并呈现子组件。 但是,当作用域槽中的内容过多时,可能会使代码难以维护。 因此,可以使用 v-slot 语法(在 Vue2 中称为 slot-scope)来优化作用域插槽。

v-slot 允许在模板中定义范围槽的名称,从而使代码更加明确和易于阅读。 以下是示例代码:

<!– In Vue 3 –>
<template>
<my-component>
<template v-slot:title=“{ name }”> {{ name }}’s Title </template>
</my-component>
</template>

<!– In Vue 2 –>
<my-component>
<template slot-scope=“{ name }”> {{ name }}’s Title </template>
</my-component>

通过使用 v-slot,我们可以在模板中指定范围插槽的名称和内容,避免组件混淆。

总结

我们希望本文呈现的 10 个优化技巧能够帮助读者更好地理解 Vue.js 并构建更高效、更可靠的 Web 应用程序。

© 版权声明

相关文章

暂无评论

暂无评论...