Skip to content

Vue 项目中,你做过哪些性能优化?

Posted on:2024年9月3日 at 13:06

在 Vue 项目中,进行性能优化通常包括以下几个方面:

1. 组件优化

const AsyncComponent = defineAsyncComponent(() =>
  import("./components/AsyncComponent.vue"),
);
<router-view v-if="componentLoaded" />
computed: {
  filteredItems() {
    return this.items.filter(item => item.active);
  }
}

2. 性能分析

3. 减少计算量

computed: {
  itemCount() {
    return this.items.length;
  }
}

4. 优化事件处理

<button @click.stop="handleClick">Click Me</button>
methods: {
  handleScroll: _.throttle(function () {
    // handle scroll event
  }, 200);
}

5. 合理使用 Vuex

mutations: {
  setUser(state, user) {
    state.user = user;
  }
}

6. 优化模板

<div v-for="item in items" :key="item.id">{{ item.name }}</div>

7. 异步数据处理

async mounted() {
  const data = await fetchData();
  this.data = data;
}

8. 缓存和懒加载

<img v-lazy="image.url" />

9. 减少第三方库使用

原文转自:https://fe.ecool.fun/topic/2e9b8935-fd13-4625-9934-c5f91d39b400