defineProps默认值是否可以这样规定 #12950
-
官网上在js中规定默认值使用的是 AI不推荐我这么做,理由是
所以AI说的每一点都被证实错误,我感觉在js中使用解构赋值默认值是完全可以的 On the official website, it is specified that in JavaScript, default values are set using: AI does not recommend doing this, for the following reasons:
So, every point made by AI has been proven wrong. I feel that using destructuring assignment for default values in JavaScript is completely feasible. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Yes, you can do this :) <script setup lang="ts">
const { foo = { a: 1 }, bar = 1 } = defineProps<{
foo: { a: number };
bar: number;
}>();
// This compiles to:
const _ = {
// ...
props: {
foo: { type: Object, required: true, default: () => ({ a: 1 }) },
bar: { type: Number, required: true, default: 1 },
},
// ...
};
</script> |
Beta Was this translation helpful? Give feedback.
-
使用默认值为对象正确的方式是函数返回 defineProps({
data: {
type: Object,
default: () => ({}) // () => { return {} }
}
}) 在以前的版本中,解构会失去响应式,现在没这问题了而已... const { data = {} } = defineProps({data: { type: Object }})
// ↓
/* sfc */{
...,
props: mergeDefault(/* raw */ { data: { type: Object } }, { data: () => ({}) }),
...
} |
Beta Was this translation helpful? Give feedback.
Yes, you can do this :)
Playground