- 仔细查看以下代码
export default {
props: {
name: String
},
setup(props) {
console.log(props.name)
}
}
此 props 对象是响应式的——即在传入新的 props 时会对其进行更新,
通过使用 watchEffect 或 watch 进行观测和响应:
- 使用watchEffect 或 watch
export default {
props: {
name: String
},
setup(props) {
watchEffect(() => {
console.log(`name is: ` + props.name)
})
}
}
- 请不要解构 props 对象,因为它会失去响应式:
export default {
props: {
name: String
},
setup({ name }) {
watchEffect(() => {
console.log(`name is: ` + name) // 没有响应式
})
}
}
- setup 中的两个参数 props, context
context:attrs、slots 和 emit 分别等同于 a t t r s 、 attrs、 attrs、slots 和 $emit 实例 property。
setup(props, context) {
context.attrs
context.slots
context.emit
context.expose
}
- 在 Vue 3.2 中新增的 expose 是一个函数,该函数允许通过公共组件实例暴露特定的 property。默认情况下,通过 ref、$parent 或 $root 获取的公共实例等同于模板所使用的内部实例。
setup(props, { expose }) {
const count = ref(0)
const reset = () => count.value = 0
const increment = () => count.value++
// 只有 reset 能被外部访问,例如通过 $refs
expose({
reset
})
// 在组件内部,模板可以访问 count 和 increment
return { count, increment }
}