如何在 vuejs 中调用对象内部引号中包裹的键?
2020-06-11
65
我正在使用 vue js,并尝试使用 props 从对象调用值。
我有此代码来调用 prop
<HeroAppearance
:eyeColor="HeroInfo.appearance.eye-color"
:gender="HeroInfo.appearance.gender"
:hairColor="HeroInfo.appearance.hair-color"
:height="HeroInfo.appearance.height[0]"
:race="HeroInfo.appearance.race"
:weight="HeroInfo.appearance.weight[0]"
/>
并且我的组件中的 props 显示
props: {
eyeColor: String,
gender: String,
hairColor: String,
height: String,
race: String,
weight: String
}
我返回的对象的眼睛颜色和头发颜色都包裹在引号中,像这样,并且除眼睛颜色和头发颜色外,所有值都显示出来,在页面加载时显示为 NaN
{
"eye-color": "Blue"
gender: "Male"
"hair-color": "No Hair"
height: Array [ "6'3", "191 cm" ]
race: "Icthyo Sapien"
}
当我加载页面时,我在控制台中收到这 2 个错误。有人能帮我了解发生了什么吗?
Property or method "color" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
和
Invalid prop: type check failed for prop "eyeColor". Expected String with value "NaN", got Number with value NaN.
2个回答
您可以使用以下语法调用带连字符的对象
HeroInfo.appearance['hair-color']
HeroInfo.appearance['eye-color']
Cre
2020-06-11
您看到了 camelCase 与 kebab-case 冲突。
eyeColor
是 camelCase,而
eye-color
是 kebab-case。
Vue.js 指南 表示对 props 使用 camelCase,但在 HTML 中使用 kebab-case:
HTML attribute names are case-insensitive, so browsers will interpret any uppercase characters as lowercase. That means when you’re using in-DOM templates, camelCased prop names need to use their kebab-cased (hyphen-delimited) equivalents.
此更改应可解决问题:
<HeroAppearance
:eye-color="HeroInfo.appearance.eyeColor"
:gender="HeroInfo.appearance.gender"
:hair-color="HeroInfo.appearance.hairColor"
:height="HeroInfo.appearance.height[0]"
:race="HeroInfo.appearance.race"
:weight="HeroInfo.appearance.weight[0]"
/>
terrymorse
2020-06-11