如何在 vuejs 中调用包含在对象内部的 qoutes 中的密钥?



我正在使用 vue js 并尝试使用 props 从对象调用值。

我有这个代码来调用道具

<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: {
eyeColor: String,
gender: String,
hairColor: String,
height: String,
race: String,
weight: String
}

我返回的对象具有眼睛颜色和头发颜色,都包裹在这样的 qoutes 中,并且显示除眼睛颜色和头发颜色之外的所有值,它们在加载页面时显示为 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.

您可以使用以下语法调用带连字符的对象

HeroInfo.appearance['hair-color']
HeroInfo.appearance['eye-color']

你看到的是骆驼与烤肉串的冲突。

eyeColor是骆驼箱,而eye-color是烤肉串箱。

Vue.js Guide 说要使用驼峰案例作为道具,但在 HTML 中使用烤肉串案例:

HTML 属性名称不区分大小写,因此浏览器会将任何大写字符解释为小写。这意味着当你使用 in-DOM 模板时,驼峰道具名称需要使用它们的烤肉串大小写(连字符分隔(等效项。

此更改应可解决此问题:

<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]"
/>

最新更新