composition api
传统的option api写组件时,需要遵循相关代码写到特定区域(methods,computed,watch,data)那么业务复杂度越高,代码量越大,越难维护,代码可复用性也不高,通过Mixins重用逻辑代码,容易发生命名冲突且关系不清。
注意:在 setup() 内部,this 不会是该活跃实例的引用,因为 setup() 是在解析其它组件选项之前被调用的,所以 setup() 内部的 this 的行为与其它选项中的 this 完全不同。
几个函数
- reactive
- watchEffect
- computed
import { reactive, ref } from 'vue'
export default {
setup() {
const state = reactive({
count: 0
})
const userId = ref(0)
const stop = watchEffect(() => {
console.log(userId)
}
stop() // 停止监听
const double = computed(() => state.count * 2)
function increment() {
state.count++
}
return {
state,
increment
}
}
}
reactive
经过reactive处理后的函数能变成响应式的数据,类似于option api里data属性里的值
watchEffect
- 与watch有什么不同?
- watchEffect不需要指定监听的属性,他会自动的收集依赖,只要我们的回调中引用了响应式的属性,而watch只能监听指定的属性。
- watch可以获取监听属性的新值,旧值,而watchEffect不可以。
- watchEffect存在的话,组件初始化的时候就会执行一次用以收集依赖,而watch不需要,因为它一开始就指定了依赖。
- 停止监听
- onInvalidate(fn): onInvalidate传入的回调会在watchEffect重新运行或停止时执行。 使用场景:监听页面id,调api获取详情,如果在调详情api的过程中,id发生了变化,就会再次调api,onInvalidate()就是为了规避此类问题
watchEffect(() => {
// 异步api调用,返回一个操作对象
const apiCall = somSyncMethod(props.userId)
onInvalidate(() => {
// 取消异步api调用
apiCall.cancel()
})
})
ref
当我们在template里面使用ref或者computed的时候,vue会自动把它们用reactive
toRefs
toRefs API提供了一个方法可以把reactive的值处理为ref
支持片段(多根节点)
<template>
<div></div>
<div></div>
</template>
自定义事件
- 事件名不存在任何自动化的大小写转换。而是触发的事件名需要完全匹配监听这个事件所用的名称
this.$emit('myEvent')
并且 v-on 事件监听器在 DOM 模板中会被自动转换为全小写 (因为 HTML 是大小写不敏感的)
defineAsyncComponent异步组件
关于异步组件可参考juejin.cn/post/684490…
动态导入的函数来延迟加载异步组件
vue2.0
components: {
HelloWorld: () => import('@/components/HelloWorld.vue')
}
vue3.0
components: {
HelloWorld: defineAsyncComponent(() => import('@/components/HelloWorld.vue'))
}
自定义指令
vue2.0
- bind - 指令绑定到元素后发生。只发生一次。
- inserted - 元素插入父 DOM 后发生。
- update - 当元素更新,但子元素尚未更新时,将调用此钩子。
- componentUpdated - 一旦组件和子级被更新,就会调用这个钩子。
- unbind - 一旦指令被移除,就会调用这个钩子。也只调用一次。
vue3.0
- bind → beforeMount
- inserted → mounted
- beforeUpdate:新的!这是在元素本身更新之前调用的,很像组件生命周期钩子。
- update → 移除!有太多的相似之处要更新,所以这是多余的,请改用 updated。
- componentUpdated → updated
- beforeUnmount:新的!与组件生命周期钩子类似,它将在卸载元素之前调用。
- unbind -> unmounted
自定义元素交互
自定义元素白名单现在在模板编译期间执行,应该通过编译器选项而不是运行时配置来配置。
Data选项
当合并来自 mixin 或 extend 的多个 data 返回值时,现在是浅层次合并的而不是深层次合并的(只合并根级属性)。
Vue3.0过滤器已删除
全局Api
不再支持按键修饰符
<input v-on:keyup.13="submit" />
<input v-on:keyup.enter="submit" />
渲染函数 API
h 现在是全局导入的,而不是作为参数自动传递。 整个 VNode props 结构是扁平的
import { h } from 'vue'
{
class: ['button', 'is-outlined'],
style: { color: '#34495E' },
id: 'submit',
innerHTML: '',
onClick: submitForm,
key: 'submit-button'
}