前后端分离之图书价格排序案例,之后端返回图片地址显示在组件上
'''注意:分别建前后端项目,前端项目只写前端代码,后端项目只写后端代码'''
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 ModelSerializerfrom .models import Bookclass BookSerializer(ModelSerializer):class Meta:model = Bookfields = '__all__'
1.3 图书后端之视图类
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin
from rest_framework.filters import OrderingFilterfrom .models import Book
from .serializer import BookSerializerclass BookView(GenericViewSet, ListModelMixin):queryset = Book.objects.all()serializer_class = BookSerializerfilter_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 pathfrom rest_framework.routers import DefaultRouterfrom app01.views import BookViewrouter = 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文件夹,然后将图片放入img2.在配置文件中加入:
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 Responseclass 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 pathfrom rest_framework.routers import DefaultRouterfrom django.views.static import serve
from django.conf import settingsfrom app01.views import ImageViewrouter = DefaultRouter()
router.register('img', ImageView, 'img')urlpatterns = [path('admin/', admin.site.urls),# 开启media访问path('media/<path:path>', 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: `<div><h1>这是远程请求的一张图片</h1><img :src="url" alt="" height="300"><br><button @click="handleSend">点我把url地址传到父组件</button></div>`,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>