需要帮助从JSON创建对象



我是Vue的新手,在将JSON更改为对象时遇到了问题。下面是我的代码示例。

<template>
<div class="characters">
<template>
<div class="stat-card">
<v-container class="mx-2">
<v-row>
<v-col cols="4">
<v-text-field
v-model="characterID"
outlined
label="Search for a character by ID"
placeholder="Enter a numeric character ID"
type="text"
append-icon="mdi-send"
@click:append="fetchCharacter(characterID)"
@keyup.enter="fetchCharacter(characterID)"
>
</v-text-field>
</v-col>
</v-row>
<v-row>
<v-card flat>
<v-card-title>Results:</v-card-title>
<v-card-text>
<pre>{{ characterData.id }}</pre>
</v-card-text>
</v-card>
</v-row>
</v-container>
</div>
</template>
</div>
</template>
<script>
export default {
data() {
return {
characterID: undefined,
characterDataJSON: {},
characterData: {},
statSlider: [
{ attribute: 'example1' },
{ attribute: 'example2' },
],
};
},
methods: {
async fetchCharacter(id) {
const numericID = parseInt(id, 10);
const requestURI = `/character/${numericID}`;
const method = 'GET';
await this.$http({ url: requestURI, data: null, method })
.then((resp) => {
this.characterDataJSON = JSON.stringify(resp.data.data, null, 't');
this.characterData = JSON.parse(this.characterDataJSON);
})
.catch(() => {
const msg = { error: 'character not found' };
this.characterDataJSON = JSON.stringify(msg, null, 't');
});
},
},
};
</script>

然而,现在

{{characterData.id}}
正在给我id。我想做这样的事情:
<script>
export default {
data() {
return {
characterID: undefined,
characterDataJSON: {},
characterData: {},
statSlider: [
{ attribute: 'example1', value: characterData.id },
{ attribute: 'example2' },
],
};
},

不过,当我这样做时,我会得到characterData是未定义的。

错误"characterData"未定义无未定义

我的最终目标是能够在滑块、下拉菜单等中使用characterData……我一直在尝试不同的东西,但我对Vue太陌生了,我不知道从哪里开始。有人知道我应该搜索什么吗?

statSlider应该是一个计算属性,如下所示:

export default {
data() {
return {
characterID: undefined,
characterDataJSON: {},
characterData: {},
};
},
computed:{
statSlider(){
return [
{ attribute: 'example1', value: this.characterData.id },
{ attribute: 'example2' },
]
}
}

您需要在data属性以及methodscomputed中使用this.

export default {
data() {
return {
characterID: undefined,
characterDataJSON: {},
characterData: {},
statSlider: [
{ attribute: 'example1', value: this.characterData.id },
//            here ======>      ^^^^^
{ attribute: 'example2' },
],
};
},

不这样做将导致undefined错误。如果你发布的代码与你的项目完全一样(没有拼写错误(,那可能是你的问题。

此外,由于characterData来自async调用,我建议在调用设置之前使用??||合并为默认值。但是,由于您已经将characterData定义为{},因此characterData.id应该自动为undefined,而不是给出错误。我只是觉得更明确一点,这样你就可以默认了。

最新更新