显示API Vue.js中的随机对象
我需要显示数组中的随机对象。数组来自API显示API Vue.js中的随机对象,vue.js,Vue.js,我需要显示数组中的随机对象。数组来自API <template> <div class="container"> <div class="box"> <p class="name"> {{chosenName.title}} </p> <p class="description"> {{chosen
<template>
<div class="container">
<div class="box">
<p class="name"> {{chosenName.title}} </p>
<p class="description"> {{chosenName.description}} </p>
<hr>
<img v-bind:src="chosenName.urlToImage" alt="">
<p class="author"> {{chosenName.author}} </p>
</div>
<div class="box">
<p class="name"> {{chosenName.title}} </p>
<p class="description"> {{chosenName.description}} </p>
<hr>
<img v-bind:src="chosenName.urlToImage" alt="">
<p class="author"> {{chosenName.author}} </p>
</div>
<button v-on:click="choose" id="choose-button">One more time</button>
</div>
</template>
@Options({
props: {
msg: String
},
data() {
return {
artworks: [],
errors: [],
chosenName: '',
}
},
created() {
axios.get(url)
.then(response => {
this.artworks = response.data.names;
})
.catch(e => {
this.errors.push(e)
})
},
methods: {
choose() {
const chosenNumber = Math.floor(Math.random() * this.artworks.length);
this.chosenName = this.artworks[chosenNumber];
console.log(chosenNumber)
}
}
})
{{chosenName.title}
{{chosenName.description}
{{chosenName.title}
{{chosenName.description}
再来一次
@选择权({
道具:{
msg:String
},
数据(){
返回{
艺术品:[],
错误:[],
chosenName:“”,
}
},
创建(){
获取(url)
。然后(响应=>{
this.artworks=response.data.names;
})
.catch(e=>{
此.errors.push(e)
})
},
方法:{
选择(){
const chosenNumber=Math.floor(Math.random()*this.artworks.length);
this.chosenName=this.artworks[chosenNumber];
console.log(chosenNumber)
}
}
})
我设法在单击时显示随机对象。我想要的是页面加载时显示的对象。我试图将函数放入挂载循环中,但没有得到像这样的好结果--->this.choose() 您需要调用
this.choose()
,如果您想让它也出现在页面加载中,则在承诺实现后,在您已安装/创建的钩子中选择()。e、 g:
mounted () {
axios.get(url)
.then(response => {
this.artworks = response.data.names;
this.choose()
})
.catch(e => {
this.errors.push(e)
})
}