細(xì)數(shù)那些Vue3中不兼容老版本的改動,避免踩坑

作者:padaker
https://padaker.com/blog/post/5fc73352cb81362ed96f2fb9
作為技術(shù)人員,隨時(shí)保持技術(shù)同步是很重要的事情。雖然Vue3已經(jīng)發(fā)布很長時(shí)間了,現(xiàn)在開始保持更新也還不晚。新項(xiàng)目可以拿來練練手XD,老項(xiàng)目就不建議升級了。
??建立項(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傳遞值。
"pageTitle"?/>
<ChildComponent??:modelValue="pageTitle"?@update:modelValue="pageTitle?=?$event"?/>
也支持綁定不同的屬性,有點(diǎn)像是v-model和sync的結(jié)合體。
"pageTitle"??v-model:content="pageContent"?/>
<ChildComponent??:title="pageTitle"?@update:title="pageTitle?=?$event"??:content="pageContent"?@update:content="pageContent?=?$event"?/>
??全局API
1. 不再使用new Vue
問題
使用new Vue會共享一個(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)在需要手動掛載根元素
app.mount("#app")
5. Tree-shaking
In Vue 3, the global and internal APIs have been restructured with tree-shaking support in mind.
沒有用到的方法(代碼)最后不會被打包到最終的包中。這可以優(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會被直接設(shè)置在組件的根元素上并且不會出現(xiàn)在$attrs中。
但是在vue3中,如果子組件只有一個(gè)根元素,則class和style會被直接設(shè)置在該元素上。超過一個(gè)則不會設(shè)置。
如果組件中設(shè)置了inheritAttrs: false,則無論如何都不會自動設(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。
最后
1.看到這里了就點(diǎn)個(gè)在看支持下吧,你的「點(diǎn)贊,在看」是我創(chuàng)作的動力。
2.關(guān)注公眾號【全棧修煉】,回復(fù)「電子書」加入獲得?160?本前端精華電子書哦
往期精文
