1. 使用 v-if 和 v-show
使用场景:当需要根据条件显示或隐藏某个元素时,可以使用 v-if 和 v-show。
优点:代码简洁易懂,执行效率高。
缺点:当条件判断比较复杂时,v-if 和 v-show 的嵌套层数过多,可读性差。
示例代码:
<template><div><div v-if="isLoading">加载中...</div><div v-else>内容</div></div>
</template><script>
export default {data() {return {isLoading: true,};},mounted() {setTimeout(() => {this.isLoading = false;}, 2000);},
};
</script>
2. 使用路由守卫(Navigation Guards)
使用场景:当需要在路由切换前后执行一些操作时,可以使用路由守卫。
优点:可以确保在路由切换过程中执行一些特定的逻辑,例如显示 loading 动画。
缺点:需要配合 Vue Router 使用,配置相对复杂。
示例代码:
import { createRouter, createWebHistory } from 'vue-router';const routes = [{path: '/',name: 'Home',component: () => import('@/views/Home.vue'),},
];const router = createRouter({history: createWebHistory(),routes,
});router.beforeEach((to, from, next) => {if (to.path === '/') {next();} else {next({ path: '/' });}
});export default router;
3. 使用异步组件(Async Components)
使用场景:当需要动态加载一个组件时,可以使用异步组件。
优点:可以提高应用程序的性能,因为只有在实际需要时才会加载组件。
缺点:需要对异步组件有一定的了解,才能正确地使用它们。
示例代码:
<template><div><AsyncComponent :is="isLoading" /></div>
</template><script>
import { defineAsyncComponent } from 'vue';export default {data() {return {isLoading: true,};},components: {AsyncComponent: defineAsyncComponent(() => import('./AsyncComponent.vue')),},mounted() {setTimeout(() => {this.isLoading = false;}, 2000);},
};
</script>
4. 使用第三方库(如 element-plus、vant 等)提供的 loading 组件
使用场景:当需要提供更好的用户体验时,可以使用第三方库提供的 loading 组件。
优点:可以提供更美观、更易于使用的 loading 组件。
缺点:可能会增加项目的体积。
示例代码:
<template><div><el-loading v-if="isLoading" fullscreen></el-loading><div v-else>内容</div></div>
</template><script>
import { ElLoading } from 'element-plus';export default {data() {return {isLoading: true,};},mounted() {setTimeout(() => {this.isLoading = false;}, 2000);},components: {ElLoading,},
};
</script>
5. 自定义全局的 loading 组件
使用场景:当需要提供更好的用户体验时,可以使用自定义的全局 loading 组件。
优点:可以提供更美观、更易于使用的 loading 组件。此外,自定义的 loading 组件可以更好地控制其显示和隐藏。
缺点:需要一定的开发成本。
MyLoading 的自定义组件:
<template><div><my-loading v-if="isLoading"></my-loading><div v-else>内容</div></div>
</template><script>
import MyLoading from './MyLoading.vue';export default {data() {return {isLoading: true,};},mounted() {setTimeout(() => {this.isLoading = false;}, 2000);},components: {MyLoading,},
};
</script>