Vue3有哪些不向下兼容的改变

4,438 阅读2分钟

作为技术人员,随时保持技术同步是很重要的事情。虽然Vue3已经发布很长时间了,现在开始保持更新也还不晚。新项目可以拿来练练手XD,老项目就不建议升级了。本篇文章整理自官方文档-BreakingChanges部分

🔥🔥建立项目

1. 使用 vite-app

npm init vite-app <project-name>

这里的vite-app是一个新项目,它的官方介绍是一个快速的WEB开发构建工具。这里我们试了一下,整个构建过程十分的快速。和以往的webpack build的方式不一样,它使用了原生ES模块加载。

2. 使用vue-cli

npm install -g @vue/cli # OR yarn global add @vue/cli
vue create <project-name>

🔥🔥v-model新语法糖

默认使用modelValue传递值。

<ChildComponent v-model="pageTitle" />

<!-- would be shorthand for: -->

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

也支持绑定不同的属性,有点像是v-modelsync的结合体。

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

<!-- would be shorthand for: -->

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

🔥🔥全局API

1. 不再使用new Vue

问题

使用new Vue会共享一个全局配置。这对于测试来说不太友好,每个测试用例都需要一个沙盒环境,全局变量去残留一些副作用。

解决

开始使用application概念,创建一个App

2. 不再用Vue.prototype

// before - Vue 2
Vue.prototype.$http = () => {}
// after - Vue 3
const app = Vue.createApp({})
app.config.globalProperties.$http = () => {}

3. 全局方法现在在app实例上

vue2.xvue3
Vue.componentapp.component
Vue.directiveapp.directive
Vue.mixinapp.mixin
Vue.useapp.use

4. 现在需要手动挂载根元素

app.mount("#app")

5. Tree-shaking

In Vue 3, the global and internal APIs have been restructured with tree-shaking support in mind.

没有用到的方法(代码)最后不会被打包到最终的包中。这可以优化项目体积。 但是用法也需要进行改变:

import { nextTick } from 'vue'

nextTick(() => {
  // something DOM-related
})

不能再使用Vue.nextTick/this.$nextTick

🔥异步组件需要显示定义

import { defineAsyncComponent } from 'vue'

const asyncPage = defineAsyncComponent(() => import('./NextPage.vue'))

🔥$attrs 将包含class和style

vue2.x中,classstyle会被直接设置在组件的根元素上并且不会出现在$attrs中。 但是在vue3中,如果子组件只有一个根元素,则classstyle会被直接设置在该元素上。超过一个则不会设置。 如果组件中设置了inheritAttrs: false,则无论如何都不会自动设置根元素的classstyle

$listeners被移除

事件监听器也被包含还在了$attrs中。

现在属性透传更方便了!

🔥指令

指令和组件生命周期更契合,并使用统一的命名。

vue2.xvue3
bindbeforeMount
insertedmounted
-beforeUpdate (新)
update (移除)-
componentUpdatedupdated
-beforeUnmount (新)
unbindunmounted

新特性fragments

允许组件有多个根元素!

template允许设置key

循环template再也不用往里面设置key了。

scopedSlots正式弃用

vue2.6中对slot进行了改版,但是仍然对scopedSlots兼容,vue3正式弃用掉scopedSlots

监听数组变化需要用deep属性啦

如果不加deep只能检测整个数组被替换。

$children 被移除

如果想访问子组件,使用$refs

事件API被移除

$on,$off,$once不再使用。2.x的EventBus方法不能再使用。

🔥🔥Filter被移除!淦

不能再用|使用filter。Sad。

参考

历史精选

  1. 如何在10分钟之内完成一个业务页面 - Vue的封装艺术
  2. 新手也能看懂的虚拟滚动实现方法
  3. Axios源码分析

原文-我的小破站