如何在vuejs中使用axios向div显示提取的数据



我是vue的新手,我正在尝试使用axios api从codeigniter后端获取博客。但我无法理解如何在div中填充。

我使用v-if,它生成了6个列表,但数据不在那里——这里还有如何处理背景图像。

json响应中有缩略图:"https://url.com/uploads/thumb213.jpg"。如何使用v-bind来展示这一点。

<script>
new Vue({
el: '#blogapp',
data () {
return {
blogs: [],
}
},
methods: {
getBlogs () {
axios
.get('https://www.happyvoyaging.com/api/blog/list?appkey="grv250531"')
.then(response => (this.blogs = response))
.catch(error => console.log(error))
},
},
mounted() {
this.getBlogs();
},
})
</script>

这是的组成部分

<div v-for="blog in blogs" class="col-md-3">
<div">
<a href="blog-post.html"></a>
<div class="banner">
<div class="banner-bg" v-bind:style="background-image:url('{{ blog.thumbnail }}');"></div>
<div class="banner-caption">
<p class="theme-blog-item-time">day ago</p>
<h5 class="title">{{ blog.title }}</h5>
<p class="desc">{{ blog.desc }}</p>
</div>
</div>
</div>
</div>

这是json 中的响应

error: {status: false, msg: ""}
response: {posts: [{id: "44", title: "Andaman Islands: The Complete Guide for Travellers",…},…], totalPages: 2}
posts: [{id: "44", title: "Andaman Islands: The Complete Guide for Travellers",…},…]
0: {id: "44", title: "Andaman Islands: The Complete Guide for Travellers",…}
1: {id: "43", title: "Russia Visa for Indians",…}
2: {id: "42", title: "Dubai Creek – Sail through the heart of Dubai",…}
3: {id: "41", title: "A Must Follow Guide To Japan Visa Requirements",…}
4: {id: "40", title: "Russia to resume issuing visas to all categories of Indian citizens",…}
5: {id: "23", title: "Trapizzino, Rome’s OG Street Food",…}
6: {id: "17", title: "Where to Eat in Rome During Holidays",…}
totalPages: 2

获取数据

axios.get()回调将响应存储在data属性中,但API数据本身包含response.posts中的博客数据,因此其属性路径为res.data.response.posts:

axios.get(/*...*/).then(res => this.blogs = res.data.response.posts)

装订样式

v-bind:style的绑定值应该是字符串或字符串的JavaScript表达式(例如模板文字或字符串串联(:

<div class="banner-bg" v-bind:style="background-image:url('{{ blog.thumbnail }}');"></div> ❌
<div class="banner-bg" v-bind:style="`background-image:url('${blog.thumbnail}');`"></div> ✅

演示

我发现问题出在getBlog函数的then块上。您正在执行此操作。blogs=response。您可以通过执行response.data.posts从响应中获取数据只需更换:

methods: {
getBlogs () {
axios
.get('https://www.happyvoyaging.com/api/blog/list?appkey="grv250531"')
.then(response => (this.blogs = response))
.catch(error => console.log(error))
},
},

带有以下代码的部件:

methods: {
getBlogs () {
axios
.get('https://www.happyvoyaging.com/api/blog/list?appkey="grv250531"')
.then(response => (this.blogs = response.data.posts))
.catch(error => console.log(error))
},
},

它应该像这个一样工作

最新更新