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

作者:padaker
https://padaker.com/blog/post/5fc73352cb81362ed96f2fb9
作为技术人员,随时保持技术同步是很重要的事情。虽然Vue3已经发布很长时间了,现在开始保持更新也还不晚。新项目可以拿来练练手XD,老项目就不建议升级了。
??建立项目
1. 使用 vite-app
npm init vite-app 
这里的vite-app是一个新项目,它的官方介绍是一个快速的WEB开发构建工具。这里我们试了一下,整个构建过程十分的快速。和以往的webpack build的方式不一样,它使用了原生ES模块加载。
2. 使用vue-cli
npm install -g @vue/cli # OR yarn global add @vue/cli
vue create 
??v-model新语法糖
默认使用modelValue传递值。
"pageTitle" />
<ChildComponent  :modelValue="pageTitle" @update:modelValue="pageTitle = $event" />
 也支持绑定不同的属性,有点像是v-model和sync的结合体。
"pageTitle"  v-model:content="pageContent" />
<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.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.
没有用到的方法(代码)最后不会被打包到最终的包中。这可以优化项目体积。
但是用法也需要进行改变:
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中,class和style会被直接设置在组件的根元素上并且不会出现在$attrs中。
但是在vue3中,如果子组件只有一个根元素,则class和style会被直接设置在该元素上。超过一个则不会设置。
如果组件中设置了inheritAttrs: false,则无论如何都不会自动设置根元素的class和style。
$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 本前端精华电子书哦
往期精文
