细数那些Vue3中不兼容老版本的改动,避免踩坑

做者:padaker前端

https://padaker.com/blog/post/5fc73352cb81362ed96f2fb9vue


做为技术人员,随时保持技术同步是很重要的事情。虽然Vue3已经发布很长时间了,如今开始保持更新也还不晚。新项目能够拿来练练手XD,老项目就不建议升级了。webpack

🔥🔥创建项目

1. 使用 vite-app

npm init vite-app <project-name>

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

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的结合体。vue-cli

<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会共享一个全局配置。这对于测试来讲不太友好,每一个测试用例都须要一个沙盒环境,全局变量去残留一些反作用。npm

解决

开始使用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.x vue3
Vue.component app.component
Vue.directive app.directive
Vue.mixin app.mixin
Vue.use app.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.app

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

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.x vue3
bind beforeMount
inserted mounted
- beforeUpdate (新)
update (移除) -
componentUpdated updated
- beforeUnmount (新)
unbind unmounted

新特性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.看到这里了就点个在看支持下吧,你的「点赞,在看」是我创做的动力。

2.关注公众号全栈修炼,回复「电子书」加入得到 160 本前端精华电子书哦

往期精文

本文分享自微信公众号 - 全栈修炼(QuanZhanXiuLian)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。

相关文章
相关标签/搜索