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

作者:格砸?
https://padaker.com/blog/post/5fc73352cb81362ed96f2fb9
作為技術(shù)人員,隨時(shí)保持技術(shù)同步是很重要的事情。雖然Vue3已經(jīng)發(fā)布很長時(shí)間了,現(xiàn)在開始保持更新也還不晚。新項(xiàng)目可以拿來練練手XD,老項(xiàng)目就不建議升級了。本篇文章整理自官方文檔-BreakingChanges部分
??建立項(xiàng)目
1. 使用 vite-app
npm?init?vite-app?
這里的vite-app是一個(gè)新項(xiàng)目,它的官方介紹是一個(gè)快速的WEB開發(fā)構(gòu)建工具。這里我們試了一下,整個(gè)構(gòu)建過程十分的快速。和以往的webpack build的方式不一樣,它使用了原生ES模塊加載。
2. 使用vue-cli
npm?install?-g?@vue/cli?#?OR?yarn?global?add?@vue/cli
vue?create?
??v-model新語法糖
默認(rèn)使用modelValue傳遞值。
<ChildComponent?v-model="pageTitle"?/>
<ChildComponent
??:modelValue="pageTitle"
??@update:modelValue="pageTitle?=?$event"
/>
也支持綁定不同的屬性,有點(diǎn)像是v-model和sync的結(jié)合體。
<ChildComponent?v-model:title="pageTitle"?v-model:content="pageContent"?/>
<ChildComponent
??:title="pageTitle"
??@update:title="pageTitle?=?$event"
??:content="pageContent"
??@update:content="pageContent?=?$event"
/>
??全局API
1. 不再使用new Vue
問題
使用new Vue會(huì)共享一個(gè)全局配置。這對于測試來說不太友好,每個(gè)測試用例都需要一個(gè)沙盒環(huán)境,全局變量去殘留一些副作用。
解決
開始使用application概念,創(chuàng)建一個(gè)App。
2. 不再用Vue.prototype
//?before?-?Vue?2
Vue.prototype.$http?=?()?=>?{}
//?after?-?Vue?3
const?app?=?Vue.createApp({})
app.config.globalProperties.$http?=?()?=>?{}
3. 全局方法現(xiàn)在在app實(shí)例上
| vue2.x | vue3 |
|---|---|
| Vue.component | app.component |
| Vue.directive | app.directive |
| Vue.mixin | app.mixin |
| Vue.use | app.use |
4. 現(xiàn)在需要手動(dòng)掛載根元素
app.mount("#app")
5. Tree-shaking
In Vue 3, the global and internal APIs have been restructured with tree-shaking support in mind.
沒有用到的方法(代碼)最后不會(huì)被打包到最終的包中。這可以優(yōu)化項(xiàng)目體積。但是用法也需要進(jìn)行改變:
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會(huì)被直接設(shè)置在組件的根元素上并且不會(huì)出現(xiàn)在$attrs中。但是在vue3中,如果子組件只有一個(gè)根元素,則class和style會(huì)被直接設(shè)置在該元素上。超過一個(gè)則不會(huì)設(shè)置。如果組件中設(shè)置了inheritAttrs: false,則無論如何都不會(huì)自動(dòng)設(shè)置根元素的class和style。
$listeners被移除
事件監(jiān)聽器也被包含還在了$attrs中。
現(xiàn)在屬性透傳更方便了!
?指令
指令和組件生命周期更契合,并使用統(tǒng)一的命名。
| vue2.x | vue3 |
|---|---|
| bind | beforeMount |
| inserted | mounted |
| - | beforeUpdate (新) |
| update (移除) | - |
| componentUpdated | updated |
| - | beforeUnmount (新) |
| unbind | unmounted |
新特性fragments
允許組件有多個(gè)根元素!
template允許設(shè)置key
循環(huán)template再也不用往里面設(shè)置key了。
scopedSlots正式棄用
vue2.6中對slot進(jìn)行了改版,但是仍然對scopedSlots兼容,vue3正式棄用掉scopedSlots
監(jiān)聽數(shù)組變化需要用deep屬性啦
如果不加deep只能檢測整個(gè)數(shù)組被替換。
$children 被移除
如果想訪問子組件,使用$refs。
事件API被移除
$on,$off,$once不再使用。2.x的EventBus方法不能再使用。
??Filter被移除!淦
不能再用|使用filter。Sad。
參考
本篇文章整理自官方文檔:https://v3.vuejs.org/guide/migration/introduction.html
—————END—————
喜歡本文的朋友,歡迎關(guān)注公眾號?程序員哆啦A夢,收看更多精彩內(nèi)容
點(diǎn)個(gè)[在看],是對小達(dá)最大的支持!
如果覺得這篇文章還不錯(cuò),來個(gè)【分享、點(diǎn)贊、在看】三連吧,讓更多的人也看到~


