Vue2和Vue3实战代码中的小差异(实时更新)

发布于:2024-07-30 ⋅ 阅读:(95) ⋅ 点赞:(0)

前言

以下文章实时更新,主打记录差异

1. 未使用自闭合标签

  104:7  error  Require self-closing on Vue.js custom components (<el-table-column>)  vue/html-self-closing

✖ 1 problem (1 error, 0 warnings)
  1 error and 0 warnings potentially fixable with the `--fix` option.

截图如下:

在这里插入图片描述

出现这类Bug是因为

Vue.js 代码中使用的 <el-table-column> 组件未使用自闭合标签,违反 vue/html-self-closing 规则

大致如下:

<el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column label="船代码" align="center" prop="shipCode"  />
<el-table-column type="selection" width="55" align="center" />

2. 事件名连字符

示例如下:

<FileForm ref="fileFormRef" :appointment-id="formData.id" :form-type="formType"  @update:totalItemCount="totalItemCount = $event"/>

会出现如下信息:149:90 warning v-on event '@update:totalItemCount' must be hyphenated vue/v-on-event-hyphenation

截图如下:

在这里插入图片描述


原理如下: Vue3 要求在模板中使用事件时,事件名必须是连字符 (kebab-case) 风格。为了修复这个警告,可以将事件名从 @update:totalItemCount 更改为 @update:total-item-count

最终修正如下:

<EnterSiteForm 
    ref="enterSiteFormRef" 
    :appointment-id="formData.id" 
    :form-type="formType"
    @update:total-item-count="totalItemCount = $event"
  />

3. 换行符

出现如下问题:

  113:22  warning  Expected a linebreak before this attribute  vue/first-attribute-linebreak

✖ 1 problem (0 errors, 1 warning)
  0 errors and 1 warning potentially fixable with the `--fix` option.

截图如下:

在这里插入图片描述

原理如下:vue/first-attribute-linebreak 规则要求在 Vue 组件的第一个属性之前应有一个换行符,以提高代码的可读性和一致性

源代码如下:

在这里插入图片描述

修正如下:

在这里插入图片描述

4. 弃用.sync

出现如下问题

  251:14  error  '.sync' modifier on 'v-bind' directive is deprecated. Use 'v-model:propName' instead  vue/no-deprecated-v-bind-sync
  255:11  error  `slot` attributes are deprecated                                                      vue/no-deprecated-slot-attribute

✖ 2 problems (2 errors, 0 warnings)
  2 errors and 0 warnings potentially fixable with the `--fix` option.

截图如下:

在这里插入图片描述

原理如下:
已弃用的 .sync 修饰符和 slot 属性
可以改用 v-model:propName 代替 .sync,并使用插槽的现代语法

源代码如下:

在这里插入图片描述

修正结果如下:

在这里插入图片描述

5. 弃用slot

错误截图如下:

在这里插入图片描述

主要的弃用slot文字说明如下:

 274:11  error  `slot` attributes are deprecated         vue/no-deprecated-slot-attribute

Vue 3 中不再支持 slot 属性

原代码(可能是类似于这样):

<span slot="footer" class="dialog-footer">
  <el-button @click="resultDialogVisible = false">关闭</el-button>
</span>

修改为:

<template #footer>
  <el-button @click="resultDialogVisible = false">关闭</el-button>
</template>