1、Object.keys()
检查对象自身可枚举属性的数量:
const isEmpty = Object.keys(obj).length === 0;
2、JSON.stringify()
将对象转为 JSON 字符串判断:
const isEmpty = JSON.stringify(obj) === '{}';
3、Reflect.ownKeys()
(包含 Symbol 属性)
const isEmpty = Reflect.ownKeys(obj).length === 0;
示例:
<template>
<div>
<p v-if="isEmpty">{{ message }}</p>
<button @click="checkObject">检查对象</button>
</div>
</template>
<script setup>
import { ref, computed } from 'vue';
const myObject = ref({}); // 响应式对象
// 方法:检查对象是否为空
const checkObject = () => {
console.log(isEmpty.value ? '对象为空' : '对象不为空');
};
// 计算属性
const isEmpty = computed(() => {
return Object.keys(myObject.value).length === 0;
});
// 动态消息
const message = computed(() =>
isEmpty.value ? '对象为空' : '对象包含数据'
);
</script>
注意事项
-
响应式对象:
使用reactive()
或ref()
创建的对象需通过.value
访问(组合式 API 中)。 -
特殊对象:
如Date
,Map
,Set
等需要额外处理,例如:// 处理 Date 对象 if (obj instanceof Date) return false; // 非空
-
性能考虑:
(1)Object.keys()
:性能最佳(推荐)JSON.stringify()
:较慢,但可处理嵌套对象Reflect.ownKeys()
:包含不可枚举属性和 Symbol - 工具函数
// utils/isEmptyObject.js export const isEmptyObject = (obj) => { if (obj === null || typeof obj !== 'object') { return true; // 非对象直接判空 } return Object.keys(obj).length === 0; }; // 在 Vue 中使用 import { isEmptyObject } from '@/utils/isEmptyObject'; const isEmpty = isEmptyObject(myObject);