Vue3中其他的改变

1,420 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第27天,点击查看活动详情

vue2 和 vue3生命周期对比

在这里插入图片描述

在这里插入图片描述

图片来源为vue官网

注意观察最后 beforeDestroydestroyed 改为了 beforeUnmountunmounted

与 2.x 版本生命周期相对应的组合式 API

  • beforeCreate -> 使用 setup()

  • created -> 使用 setup()

  • beforeMount -> onBeforeMount

  • mounted -> onMounted

  • beforeUpdate -> onBeforeUpdate

  • updated -> onUpdated

  • beforeDestroy -> onBeforeUnmount

  • destroyed -> onUnmounted

  • errorCaptured -> onErrorCaptured

全局API的转移

Vue2.x有许多全局API和配置,例如:注册全局组件,注册全局指令等

//注册全局组件
Vue.component('myButton',{
    data:()=>({
        count:0
    }),
    template:'<button @click="count++'>Clicked{{count}}</button>'
})
//注册全局指令
Vue.directive('focus',{
    inserted:el=>el.focus()
})

Vue3 中对这些API做出了调整,即Vue.xxx调整到应用实例(app)上

2.x全局API(Vue)3.x实例API()APP
Vue.config.xxxapp.config.xxx
Vue.config.productionTip移除
Vue.componentapp.component
Vue.directiveapp.directive
Vue.mixinapp.mixin
Vue.useapp.use
Vue.prototypeapp.config.globalProperties

其他改变

  • data 选项应始终声明为一个函数
  • 过渡类名的修改

Vue2.x 写法

.v-enter,
.v-leave-to {
  opacity: 0;
}
.v-leave,
.v-enter-to {
  opacity: 1;
}

Vue3.x的写法

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
.v-leave-from,
.v-enter-to {
  opacity: 1;
}
  • 移除了 keyCode 作为 v-on 的修饰符,同时也不再支持 config.keyCodes
  • 移除 v-on.native 修饰符

父组件中绑定事件

<my-component 
v-on:cloce="handleComponentEvent" 
v-on:click="handleNativeClickEvent" />

子组件中声明自定义事件

<script>
	export default({
		emits: ['close']	
	})
</script>
  • 移除过滤器(filter),用方法调用或计算属性替换过滤器

过滤器虽然这看起来很方便,但它需要一个自定义语法,打破大括号内表达式是“只是JavaScript”的假设,这不仅有学习成本,而且有实现成本!建议用方法调用或计算属性去替换过滤器