vue2.0与3.0对比,选项式 API VS 组合式 API

一、组件挂载方式不同

  1. 2.x
import Vue from 'vue'
import App from './App.vue'
import i18n from "@/i18n";
import router from "@/router";
import store from "@/store";
Vue.config.productionTip = false
new Vue({
  i18n,
  router,
  store,
  render: h => h(App)
}).$mount("#app");
  1. 3.0
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
createApp(App).use(store).use(router).mount('#app')

注意:应用实例暴露的大多数方法都会返回该同一实例,允许链式:但是.mount('#app')要放在最后,因为mount不返回应用本身。相反,它返回的是根组件实例。

二、template模版变化

  • 2.x、不支持多个根元素
  • 3.0、组件可以包含多个根节点

三、双向绑定原理变化

  1. 2.x使用Object.defineProperty
var value;
var obj = {};
Object.defineProperty(obj, 'key', {
    get: function () {
        return val;
    },
    set: function (newVal) {
        value = x;
    }
})
  1. 3.0使用ES6的新特性porxy
var obj = {};
var obj1 = new Proxy(obj, {
    get: function (target, key) {
        return target[key];
    },
    set: function (target, key, newVal) {
        target[key] = newVal;
    }
})

四、生命周期钩子函数的变化

2.x -> 3.0

beforeCreate -> setup()
created -> setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
errorCaptured -> onErrorCaptured

五、自定义指令钩子函数的变更:

2.x -> 3.0

bind → beforeMount
inserted → mounted
beforeUpdate:新的!这是在元素本身更新之前调用的,很像组件生命周期钩子。
update → 移除!有太多的相似之处要更新,所以这是多余的,请改用 updated。
componentUpdated → updated
beforeUnmount:新的!与组件生命周期钩子类似,它将在卸载元素之前调用。
unbind -> unmounted

  1. 2.x

显示此文本颜色

Vue.directive('color', { bind(el, binding, vnode) { el.style.background = binding.value } })
  1. 3.0

显示此文本颜色

const app = Vue.createApp({}) app.directive('color', { beforeMount(el, binding, vnode) { el.style.background = binding.value } })

六、变更或者废弃的方案

  1. 不能再使用Vue.nextTick/this.$nextTick,Vue3中你可以用:
import { nextTick } from 'vue'
nextTick(() => {
    // something
})
  1. 弃用refs
  2. 不再使用$on、$once、$off
  3. filter被移除,推荐使用方法调用或计算属性替换它们。
  4. Vue.prototype 替换 app.config.globalProperties
  5. 3.0版本中 v-if 总是优先于 v-for 生效。
  6. Mixin 合并行为变更浅层次执行合并;
  7. VNode Props扁平化处理;

七、tree-shaking

webapck摇树优化,仅适用于 ES Modules builds,vue3.0使tree-shaking大方异彩,应用程序采用按需加载的方式导出,没有被引用的模块不会被打包进来,减少包大小,缩小应用的加载时间。

八、更好的TypeScript集成

全面拥抱 typescript

你可能感兴趣的:(vue2.0与3.0对比,选项式 API VS 组合式 API)