Vue 3.X 相对于Vue 2.X 的版本变化
删除的部分
修改部分
-
template
组件下可以存在多个根节点 文档地址<!-- vue2.X --> <template> <div> <header>...</header> <main>...</main> <footer>...</footer> </div> </template> <!--vue3.X --> <template> <header>...</header> <main v-bind="$attrs">...</main> <footer>...</footer> </template>
-
异步组件(只说明简单的导入)导入方式变更 文档地址 ,需要将组件使用
defineAsyncComponent
包装// vue 2.X const asyncPage = () => import('./NextPage.vue') // vue 3.X import { defineAsyncComponent } from 'vue' const asyncPage = defineAsyncComponent(() => import ('./NextPage.vue'))
-
自定义指令的
API
重命名文档地址vue 2.X bind - 指令绑定到元素后发生。只发生一次。 inserted - 元素插入父 DOM 后发生。 update - 当元素更新,但子元素尚未更新时,将调用此钩子。 componentUpdated - 一旦组件和子级被更新,就会调用这个钩子。 unbind - 一旦指令被移除,就会调用这个钩子。也只调用一次。 vue 3.X bind → beforeMount inserted → mounted beforeUpdate:新的!这是在元素本身更新之前调用的,很像组件生命周期钩子 update → 移除!有太多的相似之处要更新,所以这是多余的,请改用 updated componentUpdated → updated **beforeUnmount ** 新的!与组件生命周期钩子类似,它将在卸载元素之前调用。 unbind -> unmounted
最终的API如下
const MyDirective = { beforeMount(el, binding, vnode, prevVnode) {}, mounted() {}, beforeUpdate() {}, updated() {}, beforeUnmount() {}, // 新 unmounted() {} }
-
key
值的变化文档地址对于
v-if/v-else/v-else-if
的各分支项key
将不再是必须的,vue
会自动生成唯一的key
,但是如果手动添加了key
那么所有的分支都必须使用唯一的key
<!-- Vue 2.x --> <div v-if="condition" key="yes">Yes</div> <div v-else key="no">No</div> <!-- Vue 3.x --> <div v-if="condition">Yes</div> <div v-else>No</div> <!-- 如果你手动提供了 key,那么每个分支都必须使用一个唯一的 key --> <!-- Vue 3.x --> <div v-if="condition" key="a">Yes</div> <div v-else key="b">No</div>
<template v-for>
的key
应该设置在<template>
标签上<!-- Vue 2.x --> <template v-for="item in list"> <div :key="item.id">...</div> <span :key="item.id">...</span> </template> <!-- Vue 3.x --> <template v-for="item in list" :key="item.id"> <div>...</div> <span>...</span> </template>
当使用
<template v-for>
时存在使用v-if
的子结点,key
应改为设置在<template>
标签上。<!-- Vue 2.x --> <template v-for="item in list"> <div v-if="item.isVisible" :key="item.id">...</div> <span v-else :key="item.id">...</span> </template> <!-- Vue 3.x --> <template v-for="item in list" :key="item.id"> <div v-if="item.isVisible">...</div> <span v-else>...</span> </template>
需要导入的API
-
nextTick
需要使用import { nextTick } from 'vue'
官方地址// vue 2.X import Vue from 'vue' Vue.nextTick(() => { // 一些和DOM有关的东西 }) // vue 3.X import {nextTick} from 'vue' // 第一种方法 nextTick(() => { // 一些和DOM有关的东西 }) // 第二种方法 import { shallowMount } from '@vue/test-utils' import { MyComponent } from './MyComponent.vue' import { nextTick } from 'vue' test('an async feature', async () => { const wrapper = shallowMount(MyComponent) // 执行一些DOM相关的任务 await nextTick() // 运行你的断言 })
-
v-show
导入语法import {vShow} from 'vue'
<transition> <div v-show="ok">hello</div> </transition>
组件传参时,直接在子组件中使用update
更新传递的数据一点小变化
v2
中需要在父组件中,子组件标签上,添加.sync
标识符
子组件使用<Right-Container :msg.sync="msg"/>
$emit('update:msg', 需要更新的数据)
v3
中,需要在父组件中,子组件标签上,添加v-model
子组件使用<Child1 v-model:msg="tranMsg"/>
$emit('update:msg', 需要更新的数据)