我正在尝试做一个简单的应用程序来向口袋妖怪api发送请求并将结果发送给我。
像这样: <template>
<div id="app">
<div>{{pokemon.forms}}</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "app",
data() {
return {
pokemon: {}
};
},
methods: {
requestPokemon() {
return new Promise((resolve, reject) => {
axios.get("http://pokeapi.co/api/v2/pokemon/2").then(value => {
resolve(value);
})
.catch(error => {
reject(error);
})
});
}
},
beforeMount() {
this.requestPokemon().then(value => {
pokemon = value;
}).error(error => {
console.log(error);
})
}
};
</script>
<style>
</style>
问题是我收到以下错误:
beforeMount挂钩出错:&#34; TypeError:this.requestPokemon(...)。then(...)。error不是函数&#34;
对此有何帮助??
感谢
答案 0 :(得分:0)
将错误替换为catch,正如其他人所说:
export default {
name: "app",
data() {
return {
pokemon: {}
};
},
methods: {
requestPokemon() {
return new Promise((resolve, reject) => {
axios.get("http://pokeapi.co/api/v2/pokemon/2").then(value => {
resolve(value);
})
.catch(error => {
reject(error);
})
});
}
},
beforeMount() {
this.requestPokemon().then(value => {
pokemon = value;
}).catch(error => {
console.log(error);
})
}
};
答案 1 :(得分:0)
您的beforeMount
不正确。
正如oMiKeY在回答中所说,您需要将.error
更改为.catch
您还需要将响应绑定到this.pokemon
(而不仅仅是口袋妖怪)
然后,当requestPokemon
函数返回Promise时,您需要在其中找到数据:
beforeMount() {
this.requestPokemon().then(value => {
this.pokemon = value.data
}).catch(error => {
console.log(error);
})
}