组合式API
参数
Setup
单文件组件语法 使用setup会接受两个参数:
- props
- context
props
setup函数中props是响应式的,当传入新的prop,它就被更新
export default {
props: {
title: String
},
setup(props) {
console.log(props.title)
}
}
props 是响应式的,你不能使用 ES6 解构,因为它会消除 prop 的响应性。 如果需要解构 prop,可以通过使用 setup 函数中的 toRefs 来完成此操作:
import { toRefs } from 'vue'
setup(props) {
const { title } = toRefs(props)
console.log(title.value)
}
context
context 是一个普通的 JavaScript 对象,它暴露三个组件的 property:
export default {
setup(props, context) {
// Attribute (非响应式对象)
console.log(context.attrs)
// 插槽 (非响应式对象)
console.log(context.slots)
// 触发事件 (方法)
console.log(context.emit)
}
}
它不是响应式的,这意味着你可以安全地对 context 使用 ES6 解构。
使用渲染函数
setup 还可以返回一个渲染函数,该函数可以直接使用在同一作用域中声明的响应式状态:
import { h, ref, reactive } from 'vue'
export default {
setup() {
const readersNumber = ref(0)
const book = reactive({ title: 'Vue 3 Guide' })
return () => h('div', [readersNumber.value, book.title])
}
}
生命周期钩子
和vue2.x之前的不同的是生命周期钩子前面加上 “on” 来访问组件的生命周期钩子。
下面包含如何在 setup () 内部调用生命周期钩子:
选项 API 生命周期选项和组合式 API 之间的映射
-
beforeCreate-> use setup() -
created-> use setup() -
beforeMount -> onBeforeMount
-
mounted -> onMounted
-
beforeUpdate -> onBeforeUpdate
-
updated -> onUpdated
-
beforeUnmount -> onBeforeUnmount
-
unmounted -> onUnmounted
-
errorCaptured -> onErrorCaptured
-
renderTracked -> onRenderTracked
-
renderTriggered -> onRenderTriggered
响应性API
响应性基础 API
reactive
返回对象的响应式副本,实现数据的双向绑定
const obj = reactive({ count: 0 })
片段
组件可以包含多个根节点!
<template>
<header>...</header>
<main v-bind="$attrs">...</main>
<footer>...</footer>
</template>
--end--