前后端分离-图书价格排序案例、后端返回图片地址显示在组件上(打印图片地址)

前后端分离之图书价格排序案例,之后端返回图片地址显示在组件上

'''注意:分别建前后端项目,前端项目只写前端代码,后端项目只写后端代码'''

1 图书后端

1.1 图书后端之建表
1.2 图书后端之序列化类
1.3 图书后端之视图类
1.4 图书后端之路由

2 图书前端

3 图片显示

3.1 图片显示之settings.py文件
3.2 图片显示之视图类
3.3 图片显示之路由

4 图片显示前端

1 图书后端

1.1 图书后端之建表

from django.db import models
'''
	注意事项:请在建表后,自己在数据库插入图书
'''

class Book(models.Model):
    name = models.CharField(max_length=32)
    price = models.CharField(max_length=32)

1.2 图书后端之序列化类

from rest_framework.serializers import ModelSerializer

from .models import Book


class BookSerializer(ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'

1.3 图书后端之视图类

from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from rest_framework.filters import OrderingFilter

from .models import Book
from .serializer import BookSerializer


class BookView(GenericViewSet, ListModelMixin):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    filter_backends = [OrderingFilter]
    ordering_fields = ['price']

    # 重写list方法解决跨域问题
    def list(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        
        res.headers['Access-Control-Allow-Origin'] = '*'
        
        return res

1.4 图书后端之路由

from django.contrib import admin
from django.urls import path

from rest_framework.routers import DefaultRouter

from app01.views import BookView

router = DefaultRouter()
router.register('books', BookView, 'books')

urlpatterns = [
    path('admin/', admin.site.urls),
]

urlpatterns += router.urls

2 图书前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
    <script src="js/axios.js"></script>
</head>
<body>
<div id="app">
    <button @click="handleClick">按价格排序</button>
    <ul>
        <li v-for="book in book_list">
            <h2>图书名:{{book.name}}</h2>
            <h2>图书价格:{{book.price}}</h2>
        </li>
    </ul>

</div>
</body>
</html>

<script>
    let vm = new Vue({
        el: '#app',
        data: {
            book_list: [],
            ordering: 'price'
        },
        created(){
            axios.get('http://127.0.0.1:8000/books/').then(res => {
                console.log(res.data)
                this.book_list = res.data
            });
        },
        methods: {
            handleClick(){
                if (this.ordering.indexOf('-') >= 0) {
                    this.ordering = 'price'
                } else {
                    this.ordering = '-price'
                }
            }
        },
        // 监听ordering的变化
        watch: {
            ordering() {
                // alert(this.ordering)
                axios.get('http://127.0.0.1:8000/books/?ordering=' + this.ordering).then(
                	// 箭头函数
                    res => {
                        console.log(res.data)
                        this.book_list = res.data
                    }
                );
            }
        }
    });
</script>

3 图片显示

3.1 图片显示之settings.py文件

1.在后端项目中建media文件夹
	在media文件夹建img文件夹,然后将图片放入img

2.在配置文件中加入:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

3.2 图片显示之视图类

from rest_framework.viewsets import GenericViewSet
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response


class ImageView(ViewSet):
    def list(self, request):
        return Response(
            {
                'code': 100,
                'msg': '图片返回成功',
                # 'url': 'https://img2.baidu.com/it/u=4078970732,974408090&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1695315600&t=6c20fbb0585dedf607deed8a6b97e85e'
                'url': 'http://127.0.0.1:8000/media/img/yt.jpg'
            },
            headers={'Access-Control-Allow-Origin': '*'}
        )

3.3 图片显示之路由

from django.contrib import admin
from django.urls import path

from rest_framework.routers import DefaultRouter

from django.views.static import serve
from django.conf import settings

from app01.views import ImageView

router = DefaultRouter()
router.register('img', ImageView, 'img')

urlpatterns = [
    path('admin/', admin.site.urls),
    # 开启media访问
    path('media/', serve, {'document_root': settings.MEDIA_ROOT}),
]

urlpatterns += router.urls

4 图片显示前端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
    <script src="js/axios.js"></script>
</head>
<body>
<div id="app">
    <hr>
    <lin @send="handleRecive"></lin>
</div>
</body>
</html>

<script>
    let vm = new Vue({
        el: '#app',
        data: {},
        methods: {
            handleRecive(url){
                alert(url)
            }
        },
        components: {
            lin: {
                template: `
                  

这是远程请求的一张图片


`
, data() { return { url: '' } }, created(){ axios.get('http://127.0.0.1:8000/img/').then( res => { this.url = res.data.url } ); }, methods: { handleSend(){ this.$emit('send', this.url) } } } } }); </script>

你可能感兴趣的:(vue,django,vue.js,restframework,django,axios,python,前端)