带你了解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的构造函数Vue | Vue2的实例对象vm | Vue3的对象Vue | Vue3的实例对象app | Vue3选项式API的组件实例 |
---|---|---|---|---|---|
配置上 | 在new之前进行全局配置,通过Vue.config.属性来修改 | 通过应用实例对象app来配置,比如app.config.属性 | |||
相同的配置 | errorHandler,warnHandler,performance,optionMergeStrategies | errorHandler,warnHandler,performance,optionMergeStrategies | |||
不同的配置 | silent,devtools,ignoredElements,keyCodes,productionTip | compilerOptions,globalProperties(对 Vue 2 中 Vue.prototype 使用方式的一种替代,Vue 3 已经不存在该写法了) | |||
相同属性version | Vue.version | Vue.version | app.version | ||
相同属性 | vm. d a t a , data, data,props, e l , el, el,options, p a r e n t , parent, parent,root, s l o t s , slots, slots,refs,$atrrs | d a t a , data, data,props, e l , el, el,options, p a r e n t , parent, parent,root, s l o t s , slots, slots,refs,$atrrs | |||
不同属性上 | vm. c h i l d r e n , children, children,scopedSlots, i s S e r v e r , isServer, isServer,listeners | app.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, forceUpdate,destroy | Vue.nextTick() | n e x t T i c k ( ) , nextTick(), nextTick(),forceUpdate | |
组件相关方法 | Vue.component() | defineComponent,defineAsyncComponent | app.component() | ||
相同方法 | Vue.directive(),use(),mixin() | vm. w a t c h , watch, watch,emit | app.directive(),use(),mixin() | w a t c h , watch, watch,emit | |
不同方法 | Vue.extend,set,delete,filter,compile,observable | vm. s e t , set, set,delete, o n , on, on,once,$off | Vue.createApp,createSSRApp, defineCustomElement | app.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)