VUE2.0 和VUE3.0 的区别

主要的有三点变化:

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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
原文地址:https://www.cnblogs.com/lxsunny/p/15420734.html