vue3开发中常见的代码错误或者其他相关问题小文章5.0

41. 事件修饰符在组合式 API 中的使用

错误示例: 在组合式 API 中不正确地使用事件修饰符(如 .prevent.stop),导致事件处理逻辑失效。

解决方案: 确保在 setup 函数中正确使用事件修饰符。可以通过 v-on 的选项对象来添加修饰符。

// 在 <script setup> 中
import { ref } from 'vue';

const form = ref(null);

function handleSubmit(event) {
  event.preventDefault();
  // 处理表单提交逻辑
}

<template>
  <form ref="form" @submit="handleSubmit">
    <!-- 表单内容 -->
    <button type="submit">Submit</button>
  </form>
</template>

42. 动态组件懒加载时的预加载

错误示例: 动态组件懒加载时没有配置预加载,导致用户点击时出现延迟。

解决方案: 使用 <Suspense> 组件配合 defineAsyncComponent 来实现预加载和加载状态管理。

import { defineAsyncComponent, Suspense } from 'vue';

const AsyncComponent = defineAsyncComponent(() => import('./components/MyComponent.vue'));

<template>
  <Suspense>
    <template #default>
      <AsyncComponent />
    </template>
    <template #fallback>
      <div>Loading...</div>
    </template>
  </Suspense>
</template>

43. 全局插槽和作用域插槽的传递

错误示例: 在父组件中定义的插槽无法正确传递给子组件,或者作用域插槽的数据绑定失败。

解决方案: 确保正确使用 v-slot 指令,并且传递必要的数据给子组件。

<!-- 父组件 -->
<ChildComponent v-slot="{ data }">
  <p>{{ data }}</p>
</ChildComponent>

<!-- 子组件 -->
<template>
  <slot :data="someData"></slot>
</template>

<script setup>
import { ref } from 'vue';
const someData = ref('Hello from child');
</script>

44. Vue Router 动态路由参数的类型检查

错误示例: 动态路由参数未进行类型检查,导致潜在的运行时错误。

解决方案: 使用 TypeScript 和 Vue Router 的类型定义来确保路由参数的正确性。

import { RouteRecordRaw } from 'vue-router';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/user/:id',
    component: User,
    props: (route) => ({
      id: parseInt(route.params.id as string, 10),
    }),
  },
];

45. 异步操作中的错误处理

错误示例: 异步操作中没有适当的错误处理机制,导致未捕获的错误影响用户体验。

解决方案: 使用 try...catch 结构或 .catch() 方法来处理异步操作中的错误。

async function fetchData() {
  try {
    const response = await fetch('/api/data');
    if (!response.ok) throw new Error('Network response was not ok');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('There was a problem with the fetch operation:', error);
  }
}

46. 样式模块化和作用域

错误示例: 全局样式和局部样式冲突,导致样式应用不一致。

解决方案: 使用 CSS Modules 或者 scoped 样式来避免冲突。

/* 使用 CSS Modules */
<style module>
.button {
  background-color: blue;
}
</style>

<template>
  <button :class="$style.button">Click me</button>
</template>

47. 响应式图片加载

错误示例: 不同设备上图片加载不当,影响页面性能和用户体验。

解决方案: 使用 <picture> 标签和 srcset 属性来实现响应式图片加载。

<picture>
  <source media="(min-width: 650px)" srcset="img/image-large.jpg">
  <source media="(min-width: 465px)" srcset="img/image-medium.jpg">
  <img src="img/image-small.jpg" alt="Responsive image">
</picture>

48. 第三方库的按需引入

错误示例: 引入了整个第三方库,导致打包体积过大。

解决方案: 使用按需引入的方式只加载所需的模块。

// Ant Design Vue 按需引入
import { Button, message } from 'ant-design-vue';
import 'ant-design-vue/lib/button/style/css';
import 'ant-design-vue/lib/message/style/css';

49. 国际化资源懒加载

错误示例: 一次性加载所有语言包,增加了初始加载时间。

解决方案: 根据用户选择的语言按需加载相应的语言包。

import i18n from './i18n'; // 假设这是你的 i18n 实例

async function loadLanguage(lang) {
  const messages = await import(`./locales/${lang}.json`);
  i18n.global.setLocaleMessage(lang, messages.default);
  i18n.global.locale = lang;
}

50. Vite 插件配置错误

错误示例: Vite 配置文件中插件配置不当,导致开发服务器启动失败或构建出错。

解决方案: 确保 Vite 插件配置正确,并且按照官方文档进行设置。

// vite.config.js
import vue from '@vitejs/plugin-vue';
import path from 'path';

export default {
  plugins: [vue()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
};

5.0 - 完

posted @ 2024-12-16 10:20  爱上大树的小猪  阅读(80)  评论(0)    收藏  举报