VUE2.0 和VUE3.0 的區別
阿新 • • 發佈:2021-10-18
主要的有三點變化:
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
函式。
作者:隨筆記呀 連結:https://www.jianshu.com/p/d3f973433274 來源:簡書 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。