vue3 新写法

1、v-mdel

  • 非兼容:用于自定义组件时,v-model prop 和事件默认名称已更改:
    • prop:value -> modelValue
    • 事件:input -> update:modelValue
  • 非兼容:v-bind 的 .sync 修饰符和组件的 model 选项已移除,可在 v-model 上加一个参数代替;

vue2 双向绑定写法,使用.sync

<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />


简写
<ChildComponent :title.sync="pageTitle" />

vue3 写法

<ChildComponent v-model:title="pageTitle" />

<!-- 是以下的简写: -->

<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />

并且可以使用多个

<ChildComponent v-model:title="pageTitle" v-model:content="pageContent" />

<!-- 是以下的简写: -->

<ChildComponent
  :title="pageTitle"
  @update:title="pageTitle = $event"
  :content="pageContent"
  @update:content="pageContent = $event"
/>

2、v-for

vue2 中 <template> 标签不能拥有 key,可以为其每个子节点分别设置 key

在 Vue 3.x 中,key 则应该被设置在 <template> 标签上。

<!-- Vue 3.x -->
<template v-for="item in list" :key="item.id">
  <div>...</div>
  <span>...</span>
</template>

3、v-if 与 v-for 的优先级对比

非兼容:两者作用于同一个元素上时,v-if 会拥有比 v-for 更高的优先级。

2.x 语法

2.x 版本中在一个元素上同时使用 v-if 和 v-for 时,v-for 会优先作用。

3.x 语法

3.x 版本中 v-if 总是优先于 v-for 生效。

.native

4、.native移除

为什么需要 .native

    1. 自定义组件的特殊性
      当你在自定义组件上绑定事件(如 @click)时,Vue 默认会将其视为自定义事件(需要通过 $emit 触发),而不是原生 DOM 事件。

    2. 穿透到根元素
      添加 .native 后,事件会直接绑定到组件的根原生 DOM 元素上,跳过自定义事件机制。

Vue 3 中的变化

在 Vue 3 中,.native 修饰符已被移除,原因如下:

  1. 隐式行为问题:.native 的行为不够直观,容易让人困惑。

  2. 替代方案:Vue 3 推荐显式地使用 emits 选项声明自定义事件,未声明的事件会被视为原生事件。

posted @ 2025-06-26 15:15  风花一世月  阅读(12)  评论(0)    收藏  举报