composition api-组合式api
setup
-
参数:
props:因为props是响应式的,不可以解构,如果解构将失去响应式,如果需要解构 prop,可以通过使用
setup
函数中的toRefs
来完成此操作import { toRefs } from 'vue' setup(props) { const { title } = toRefs(props) console.log(title.value) }
context:是一个普通的js对象,{attrs, slots, emit},所以可以去解构
export default { setup(props, context) { // Attribute (有状态、非响应式对象,不要解构) console.log(context.attrs) // 插槽 (有状态、非响应式对象,不要解构) console.log(context.slots) // 触发事件 (方法) console.log(context.emit) } }
-
访问组件的属性
执行
setup
时,组件实例尚未被创建。因此,你只能访问以下 property:props
attrs
slots
emit
换句话说,你将无法访问以下组件选项:
data
computed
methods
-
结合模板使用
返回的对象,可以在template里直接使用
-
this:没有this
reactive
将普通对象包装成可响应式
ref函数
生成响应式ref变量对象=>创建了一个响应式引用,并且拥有一个value属性,该变量的值放在value属性上面
// 生成
let name = ref('test')
// 在setup函数中返回该变量
// 模板中使用
{
{
name}}
// 修改变量值
name.value = 'world' // 注意一定是修改value属性
toRefs函数
生命周期钩子
在setup中使用的钩子函数
选项式 API | Hook inside 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 |
watch
import {
ref, watch } from 'vue'
// 例子
const counter = ref(0)
watch(counter, (newValue, oldValue) => {
console.log('The new counter value is: ' + counter.value)
})
// 语法
watch(一个响应式引用或者想要监听的getter,回调函数,配置选项)
computed
let cName = computed(_ => {
return name.value+' computed'
})