介绍
- 为了开始使用组合式 API,我们首先需要一个可以实际使用它的地方。在 Vue 组件中,我们将此位置称为
setup
。 - 新的
setup
选项在组件创建之前执行,一旦props
被解析,就将作为组合式 API 的入口。
在
setup
中你应该避免使用this
,因为它不会找到组件实例。setup
的调用发生在
data property
、computed property
或methods
被解析之前,所以它们无法在setup
中被获取。
在vue组件中使用如下
<template>
<div>{{ msg }}</div>
</template>
<script>
import { defineComponent } from "vue";
export default defineComponent({
name: "About",
setup() {
const msg = "hello"
return {
msg
};
},
});
</script>
使用
使用 setup
函数时,它将接收两个参数:
props
context
props
第一个参数,props
是响应式的,当传入新的prop
时,将被更新。
注意:不能够使用ES6解构,因为会消除响应性。
如果需要使用解构prop
,可以使用toRefs
方法来完成。
import { toRefs } from 'vue'
export default {
props:{
title:String
},
setup(props){
const { title } = toRefs(props)
}
}
context
传递给 setup
函数的第二个参数是 context
。context
是一个普通的 JavaScript 对象,它暴露三个组件的 property:
export default {
setup(props, context) {
// Attribute (非响应式对象)
console.log(context.attrs)
// 插槽 (非响应式对象)
console.log(context.slots)
// 触发事件 (方法),最常用的
console.log(context.emit)
}
}
context
是一个普通的 JavaScript 对象,也就是说,它不是响应式的,这意味着你可以安全地对 context
使用 ES6 解构。
export default {
setup(props, { attrs, slots, emit }) {
...
}
}
attrs
和 slots
是有状态的对象,它们总是会随组件本身的更新而更新。这意味着你应该避免对它们进行解构,并始终以 attrs.x
或 slots.x
的方式引用 property。请注意,与 props
不同,attrs
和 slots
是非响应式的。如果你打算根据 attrs
或 slots
更改应用副作用,那么应该在 onUpdated
生命周期钩子中执行此操作。
生命周期函数
选项式 API | 组合式API setup |
---|---|
beforeCreate | Not needed* |
created | Not needed* |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeUnmount | onBeforeUnmount |
unmounted | onUnmounted |
errorCaptured | onErrorCaptured |
renderTracked | onRenderTracked |
renderTriggered | onRenderTriggered |
这些钩子函数编写的代码都应该直接在setup中编写。
<script>
import {
defineComponent,
onBeforeMount,
onBeforeUpdate,
onMounted,
onUnmounted,
onUpdated,
} from "vue";
export default defineComponent({
setup() {
console.log("beforeCreate");
console.log("created");
onBeforeMount(() => {
console.log("onBeforeMount");
});
onMounted(() => {
console.log("onMount");
});
onBeforeUpdate(() => {
console.log(onBeforeUpdate);
});
onUpdated(() => {
console.log(onUpdated);
});
onUnmounted(() => {
console.log(onUnmounted);
});
return {};
},
});
</script>