1:vue2和vue3雙向數據綁定原理發生了改變
vue2
的雙向數據綁定是利用ES5
的一個APIObject.definePropert()
對數據進行劫持,結合發布訂閱模式的方式來實現的。
vue3
中使用了ES6
的Proxy
API對數據代理。
相比vue2.x
,使用proxy
的優勢如下:
-
defineProperty
只能監聽某個屬性,不能對全對象監聽 - 可以省去
for in
,閉包等內容來提升效率(直接綁定整個對象即可) - 可以監聽數組,不用再去單獨的對數組做特異性操作
vue3.x
可以檢測到數組內部數據的變化。
2: vue2和vue3定義數據變量和方法的改變
在vue2
中定義數據變量是data(){}
,創建的方法要在methods:{}
中。
而在vue3
中直接在setup(){}
中,在這里面定義的變量和方法因為最終要在模板中使用,所以最后都得 return
。
如:
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
name: 'App',
setup() {
//使用ref,說明這個數組就是全局在面板中可以使用了
const girls = ref(['美女1','美女2','美女3'])
const selectGirl = ref('2')
//設置一個函數
const selectGirlFun = (index: number) => {
//改變selectGirl的值要加value
//要得到值要加value ,這些都因為使用了ref函數
selectGirl.value = girls.value[index]
}
//在標簽中使用的變量要使用return
//為什么要使用return,因為有的不需要在標簽中使用的就不用return
return{
girls,
selectGirl,
selectGirlFun
}
},
});
</script>
3: vue2和vue3生命周期鉤子函數的不同
-
vue2
中的生命周期-
beforeCreate
組件創建之前 -
created
組件創建之后 -
beforeMount
組價掛載到頁面之前執行 -
mounted
組件掛載到頁面之后執行 -
beforeUpdate
組件更新之前 -
updated
組件更新之后
-
-
vue3
中的生命周期-
setup
開始創建組件 -
onBeforeMount
組價掛載到頁面之前執行 -
onMounted
組件掛載到頁面之后執行 -
onBeforeUpdate
組件更新之前 -
onUpdated
組件更新之后
而且Vue3.x
生命周期在調用前需要先進行引入。
如:
-
import {
reactive,
toRefs,
onMounted,
onBeforeMount,
onBeforeUpdate,
onUpdated,
} from "vue";
- 來一個總的生命周期對比,這樣更便于記憶
Vue2--------------vue3
beforeCreate -> setup()
created -> setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
activated -> onActivated
deactivated -> onDeactivated
errorCaptured -> onErrorCaptured
除了這些鉤子函數外,Vue3.x
還增加了onRenderTracked
和onRenderTriggered
函數。
3: vue3中新加入了TypeScript和PWA的支持
這篇文章持續更新喲