带你了解Vue2和Vue3区别(一)——Vue和Vue实例属性和方法

带你了解Vue2和Vue3区别(一)——Vue和Vue实例属性和方法

Vue

vue2的Vue为构造函数,而vue3的Vue为对象。

typeof Vue // vue2输出为"function",vue3输出为"object"

在创建一个实例和挂载上

// vue2 通过选项"el",将页面上已存在的 DOM 元素作为 Vue 实例的挂载目标
const vm = new Vue({
    el: "#app",
    /* 其他选项 */
})

// vue2 通过实例方法"$mount"手动地挂载一个未挂载的实例。
const vm = new Vue({
    /* 选项 */
})
vm.$mount("#app")

// vue3 通过全局方法createApp()创建实例,通过实例方法mount挂载实例
// 无"el"选项
const app = Vue.createApp({
    /* 根组件选项 */
})
app.mount("#app")

vue3没了vue2的"el"选项,从而生命周期的初始阶段上有些变化。同时,vue3的实例方法“mount”没了vue2前面的"$"。

Vue和Vue实例属性和方法

Vue和Vue实例属性和方法完整对比API,如下表所示。

对比角度Vue2的构造函数VueVue2的实例对象vmVue3的对象VueVue3的实例对象appVue3选项式API的组件实例
配置上在new之前进行全局配置,通过Vue.config.属性来修改通过应用实例对象app来配置,比如app.config.属性
相同的配置errorHandler,warnHandler,performance,optionMergeStrategieserrorHandler,warnHandler,performance,optionMergeStrategies
不同的配置silent,devtools,ignoredElements,keyCodes,productionTipcompilerOptions,globalProperties(对 Vue 2 中 Vue.prototype 使用方式的一种替代,Vue 3 已经不存在该写法了)
相同属性versionVue.versionVue.versionapp.version
相同属性vm. d a t a , data, dataprops, e l , el, eloptions, p a r e n t , parent, parentroot, s l o t s , slots, slotsrefs,$atrrs d a t a , data, dataprops, e l , el, eloptions, p a r e n t , parent, parentroot, s l o t s , slots, slotsrefs,$atrrs
不同属性上vm. c h i l d r e n , children, childrenscopedSlots, i s S e r v e r , isServer, isServerlistenersapp.config,version
生命周期相关方法Vue.nextTick()vm. n e x t T i c k ( ) , nextTick(), nextTick()mount, f o r c e U p d a t e , forceUpdate, forceUpdatedestroyVue.nextTick() n e x t T i c k ( ) , nextTick(), nextTick()forceUpdate
组件相关方法Vue.component()defineComponent,defineAsyncComponentapp.component()
相同方法Vue.directive(),use(),mixin()vm. w a t c h , watch, watchemitapp.directive(),use(),mixin() w a t c h , watch, watchemit
不同方法Vue.extend,set,delete,filter,compile,observablevm. s e t , set, setdelete, o n , on, ononce,$offVue.createApp,createSSRApp, defineCustomElementapp.provide,runWithContextapp

从上表可看出,**大部分Vue2构建函数Vue上的属性和方法都迁移到Vue3的实例对象app上。**比如,Vue2进行全局注册属性,需要在new实例之前在构造函数上运行方法component()。而Vue3是在使用Vue对象的createApp()方法创建实例app后,然后通过实例app的component()。同理,进行注册全局指令(directive),全局使用插件(use)和全局混入(mixin),也是如此。

同时,几乎所有Vue2实例对象vm的所有属性和方法都迁移到Vue3选项式API的组件实例上
下一章将介绍Vue2的选项和Vue3的选项式API的区别

参考文献

Vue2 API — Vue.js (vuejs.org)
Vue3 API 参考 | Vue.js (vuejs.org)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值