VUE3 入门教程 Vue 3.0 在prop的默认函数中访问this

2024-02-25 开发教程 VUE3 入门教程 匿名 0

生成 prop 默认值的工厂函数不再能访问 this

替代方案:

  • 把组件接收到的原始 prop 作为参数传递给默认函数;
  • 注入 API 可以在默认函数中使用。
import { inject } from 'vue'
export default {
props: {
theme: {
default (props) {
// `props` 是传递给组件的原始值。
// 在任何类型/默认强制转换之前
// 也可以使用 `inject` 来访问注入的 property
return inject('theme', 'default-theme')
}
}
}
}