Vue判断对象是否为空

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue判断对象是否为空

huayang183   2022-09-08 我要评论

Vue判断对象是否为空

方法一

将对象转JSON,如果为空集合{} ,那么就是空对象

JSON.stringify(object)=='{}'

方法二

判断对象的长度,如果为零,那就是空对象

Object.keys(object).length==0

Vue判断对象为空|cannot read property ‘xx‘ of undefined

vue中判断对象为空

结构体如下

在调用text.value时,因默认情况下text为空报错

解决方法

使用 typeof 对text进行判断是否为 undefined

存在问题

当判断text.value时会失效,因为text就不存在,value更不用说了所以直接判断text就可以了

依据

在ESLint 0.5.0中引入 typeof操作符,用于强制与有效的字符串进行比较 ESLint文档地址

typeof通常与以下字符串比较:undefined、object、boolean、number、string、symbol和bigint

与其他字符串比较时,通常是个书写错误

Options

该规则有一个对象选项:

"requireStringLiterals": true 要求 typeof 表达式只与字符串字面量或其它 typeof 表达式 进行比较,禁止与其它值进行比较。

错误 代码示例:

/*eslint valid-typeof: "error"*/
typeof foo === "strnig"
typeof foo == "undefimed"
typeof bar != "nunber"
typeof bar !== "fucntion"

正确 代码示例:

/*eslint valid-typeof: "error"*/
typeof foo === "string"
typeof bar == "undefined"
typeof foo === baz
typeof bar === typeof qux

选项 { "requireStringLiterals": true } 的 错误 代码示例:

typeof foo === undefined
typeof bar == Object
typeof baz === "strnig"
typeof qux === "some invalid type"
typeof baz === anotherVariable
typeof foo == 5

选项 { "requireStringLiterals": true } 的 正确 代码示例:

typeof foo === "undefined"
typeof bar == "object"
typeof baz === "string"
typeof bar === typeof qux

v-for与v-if 同时存在时,渲染错误

解决方法

外层加一个template把v-for放在template标签中

v-for中的key理解

v-for 是循环,可以把数组中的元素遍历出来,

vue3中,必须要有key参数,key就相当于索引, 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们