setup 函数
在 Vue 中我们就是在 setup 函数中使用 Composition API 来编写代码。
setup 其实就是组件的另外一个选项,只不过这个选项强大到我们可以用它来替代之前所编写的大部分其他选项,比如 data、methods、computed、watch、生命周期等等(不包括 props 跟 directives)。
setup 函数的参数
setup 函数有两个参数,props 和 context
props 就是父组件传过来的自定义属性。
export default {
props: {
message: {
type: String,
required: true
}
}
}
在 setup 函数中如果我们想要使用父组件传过来的自定义属性,不能通过 this.props 来获取,因为 this 是不可用的。可以直接使用 setup 函数的 props 参数
export default {
props: {
message: {
type: String,
required: true
}
},
setup(props) {
console.log(this.props); // 不可用
console.log(props);
}
}
setup 函数的返回值
setup 函数的返回值返回一个对象,可以在模板 template 中被使用,也就是说我们可以通过 setup 的返回值来替代 data 选项,或者是可以返回一个执行函数来代替在 methods 中定义的方法:
export default {
setup() {
let age = 20
let increment = () => {
console.log('abc')
}
return {
name: 'caohan',
age,
increment
}
}
}
<template>
<div>
<h4>{{ name }}</h4>
<h4>{{ age }}</h4>
<button @click="increment">按钮</button>
</div>
</template>
setup 函数中的 this
在 setup 函数中是不能使用 this 的。因为底层代码中没有进行 this 的绑定,所以 this 并没有指向当前组件实例。并且在 setup 被调用之前,data 、computed 、methods 等都没有被解析,所以无法在 setup 中获取 this