Vue组件中的代码如下:

 1.在methods中定义获取轮播图图片的方法:get_imgs(),通过ajax对后台进行请求。

 2.在created中调用get_imgs(),在created中的方法会在模板渲染成html前调用,即通常初始化某些属性值,然后再渲染成视图,

不理解的可以自己百度Vue的生命周期。

 3.然后在模板中使用v-for进行渲染,注意:要写入一个key属性,并且<img>标签中的src要写成你后台定义的键。

  (自己老眼昏花,把item.img_url写成了item.url,最后图片不显示,控制台也没有报错,找半天,还是不够细)

 4.在做完这些你会出现CORS跨域请求的报错信息。(解决办法:看这篇文章

 

前端模板代码如下:

<template>
    <div>
        <mt-swipe :auto="4000">
            <mt-swipe-item v-for="item in body" :key="item.id"><img :src="item.img_url"></mt-swipe-item>
        </mt-swipe>
        <h3>HomeContainer</h3>
    </div>
</template>
<script>
export default {
    data(){
        var body = null;
        return {body}
    },
    methods:{
        get_imgs(){
            this.$http.get("http://127.0.0.1:8000/").then(result =>{
                console.log('Success');
                console.log(result.body);
                this.body = result.body;
            },result => {
                console.log('Failed')
            })
        },
    },
    created:function () {
        this.get_imgs()
    }
}

</script>
<style lang="scss" scoped>
    .mint-swipe{
        height:200px;
        .mint-swipe-item{
            img{
                width: 100%;
                height: 100%;
            }
        }

    }
</style>

后端视图代码如下:

from django.shortcuts import render
from django.http import HttpResponse
import json


# Create your views here.


def get_swipes(request):
    result = [
        { "id":1, "img_url": "http://127.0.0.1:8000/static/1.jpg"},
        { "id":2, "img_url": "http://127.0.0.1:8000/static/2.jpg"},
        { "id":3, "img_url": "http://127.0.0.1:8000/static/3.jpg"}
    ]
    return HttpResponse(json.dumps(result,ensure_ascii=False))

 

Logo

前往低代码交流专区

更多推荐