defineProps和加props区别
在vue3中下面两个写法有什么区别?
defineProps({
userId: {
type: Boolean,
default: true
}
});
const props = defineProps({
userId: {
type: Boolean,
default: true
}
});
区别
这两个写法在 运行时行为上是完全一样的,区别主要在于是否接收返回值,从而影响你在 <script setup> 中如何使用 props。
1️⃣ 不接收返回值的写法
defineProps({
userId: {
type: Boolean,
default: true
}
});
👉 特点:
defineProps是 编译宏(compiler macro),在 Vue 3 的<script setup>中会被编译掉- 虽然没有赋值给变量,但 props 仍然可以直接在模板中使用
- 在
<script setup>代码里无法直接访问userId(除非解构或用变量接收)
👉 适用场景:
- 你只在 template 模板中使用 props
- 不需要在 JS 逻辑中访问 props
2️⃣ 接收返回值的写法
const props = defineProps({
userId: {
type: Boolean,
default: true
}
});
👉 特点:
defineProps返回一个props对象- 可以在
<script setup>中通过props.userId使用 - 在 template 中仍然可以直接用
userId(不需要写props.userId)
👉 适用场景:
- 需要在 JS 逻辑中使用 props(比如计算、watch、条件判断)
⚠️ 一个容易忽略的点
即使你写了:
const props = defineProps(...)
在 template 里仍然可以这样写:
{{ userId }}
👉 因为 <script setup> 会自动把 props 暴露给模板(解构式暴露)
✔️ 总结
| 写法 | 是否可在 script 中使用 | 是否可在 template 中使用 |
|---|---|---|
defineProps(...) |
❌ 不方便直接用 | ✅ 可以 |
const props = defineProps(...) |
✅ 可以 (props.xxx) |
✅ 可以 |
👉 建议
如果你不确定:
优先用
const props = defineProps()
因为:
- 可读性更好
- 后续需要在 script 中用 props 时不用改结构
使用的时候需要使用.value吗?
结论先说清楚:不需要 .value。
✅ 为什么不需要 .value
const props = defineProps({
userId: Boolean
});
这里的 props:
- 不是
ref - 而是一个由 Vue 3 提供的 响应式对象(reactive proxy)
所以你访问时是:
props.userId // ✅ 正确
props.userId.value // ❌ 错误
🧠 对比一下就很清楚
| 类型 | 写法 | 是否需要 .value |
|---|---|---|
ref |
const count = ref(0) |
✅ count.value |
reactive |
const obj = reactive({ a: 1 }) |
❌ obj.a |
props |
const props = defineProps() |
❌ props.xxx |
👉 props 的行为更接近 reactive,而不是 ref
⚠️ 一个常见坑(非常重要)
如果你这样写:
const { userId } = defineProps({
userId: Boolean
});
👉 这里的 userId:
- 不是响应式的
- 只是一个普通变量(值拷贝)
✔️ 正确做法(保持响应式)
如果你想解构又保持响应式,需要用:
import { toRefs } from 'vue';
const props = defineProps({
userId: Boolean
});
const { userId } = toRefs(props);
👉 这时候:
userId.value // ✅ 需要 .value,因为它变成 ref 了
🔚 总结一句话
props.xxx→ ❌ 不用.valuetoRefs(props).xxx→ ✅ 需要.valueref()→ ✅ 需要.value