day69 作业


3、完成基础前后台分类的数据展示类网站
	封装导航栏Nav小组件,完成各页面的跳转,在需要导航栏的页面中渲染Nav小组件
	在主页Home组件中,写一个轮播图(bs和element都要提供),完成后台数据的轮播展示
	将汽车主页数据渲染以及详情页数据渲染的数据,都放在后台(用mysql数据库存储),完成后台数据的渲染,前台父子组件以及组件间的传参

前端

vue main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false;

//全局css
require('@/assets/css/global.css');

//全局js
import settings from '@/assets/js/settings'
Vue.prototype.$settings=settings

//配置axios
import axios from 'axios'
Vue.prototype.$axios=axios;

//配置element-ui
import  ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI);

//配置bootstrap,前提是配置jQuery
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.css'
//或者
// import Bootstrap from'bootstrap'
// import 'bootstrap/dist/css/bootstrap.css'
// Vue.use(Bootstrap)

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

vue CarTag.vue 小组件

<template>
    <div class="car-tag">
        <router-link :to="`/car/detail/${car.id}`">
            <img :src="car.img" alt="">
        <h4>
            <span>{{ car.title }}</span>
        </h4>
        </router-link>
    </div>
</template>

<script>
    export default {
        name: "CarTag",
        props:['car']
    }
</script>

<style scoped>
    .car-tag {
        border-radius: 10px;
        overflow: hidden;
         200px;
        height: 320px;
        float: left;
        margin-right: 25px;
        margin-bottom: 25px;
        background-color: beige;
        cursor: pointer;
    }

    .car-tag a.router-link-active {
        display: block;
    }

    .car-tag:nth-child(5n) {  /* 每五个car-tag右边距为0*/
        margin-right: 0;
    }

    .car-tag img {
        height: 280px;
         100%;
    }

    .car-tag h4 {
        margin: 5px auto;
        text-align: center;
    }
</style>

vue Nav.vue小组件

<template>
    <div class="nav">
        <ul>
            <li>
                <router-link to="/">主 页</router-link>
            </li>
            <li>
                <router-link to="/car">汽 车</router-link>
            </li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: "Nav"
    }
</script>

<style scoped>
    .nav {
        height: 60px;
        background-color: aqua;
    }

    .nav ul {
         1100px;
        margin: 0 auto;
    }

    .nav li {
        float: left;
        padding: 15px 20px 0;
    }

    .nav a {
        border-bottom: 3px solid  transparent;
        padding: 1px;
    }

    .nav a.router-link-exact-active {
        color: darkblue;
        border-bottom-color: orange;
    }
</style>

vue Home.vue 页面

<template>
    <div class="home">
        <Nav></Nav>
        <h1>
            <span @click="goCarPage">欢迎来到汽车系统</span>
        </h1>
        <div class="block">
            <span class="demonstration">默认 Hover 指示器触发</span>
            <el-carousel height="320px" >
                <el-carousel-item v-for="item in cars" :key="item">
                    <div style="height: 320px; 200px;margin: auto">
                        <img :src="item.img" alt="" style=" 100%">
                    </div>
                </el-carousel-item>
            </el-carousel>
        </div>
    </div>
</template>

<script>
    import Nav from '../components/Nav'
    export default {
        name: "Home",
        components: {
            Nav
        },
        data() {
            return {
                cars:[]
            }
        },
        methods: {
            goCarPage() {
                if (this.$router.path !== '/car') {
                    this.$router.push('/car')
                }
            }
        },
        created() {
            this.$axios({
                url: this.$settings.base_url + '/get_cars/',
                method: 'post',
            }).then(response => {
                this.cars = response.data;
            }).catch(error => {//网络状态码为4xx  5xx
                console.log('异常', error.response)
            })
        }
    }

</script>

<style scoped>
    h1 {
        text-align: center;
        margin-top: 60px;
    }

    h1 sapn {
        cursor: pointer;
        font: bold 60px/70px 'STSong';
    }

    .el-carousel__item h3 {
        color: #475669;
        font-size: 14px;
        opacity: 0.75;
        line-height: 150px;
        margin: 0;
    }

    .block {
         800px;
        margin: auto;
    }



    .el-carousel__item:nth-child(2n) {
        background-color: #99a9bf;
    }

    .el-carousel__item:nth-child(2n+1) {
        background-color: #d3dce6;
    }
</style>

vue Car.vue 页面

<template>
    <div class="home">
        <Nav></Nav>
        <h1>
            <span @click="goCarPage">欢迎来到汽车系统</span>
        </h1>
        <div class="block">
            <span class="demonstration">默认 Hover 指示器触发</span>
            <el-carousel height="320px" >
                <el-carousel-item v-for="item in cars" :key="item">
                    <div style="height: 320px; 200px;margin: auto">
                        <img :src="item.img" alt="" style=" 100%">
                    </div>
                </el-carousel-item>
            </el-carousel>
        </div>
    </div>
</template>

<script>
    import Nav from '../components/Nav'
    export default {
        name: "Home",
        components: {
            Nav
        },
        data() {
            return {
                cars:[]
            }
        },
        methods: {
            goCarPage() {
                if (this.$router.path !== '/car') {
                    this.$router.push('/car')
                }
            }
        },
        created() {
            this.$axios({
                url: this.$settings.base_url + '/get_cars/',
                method: 'post',
            }).then(response => {
                this.cars = response.data;
            }).catch(error => {//网络状态码为4xx  5xx
                console.log('异常', error.response)
            })
        }
    }

</script>

<style scoped>
    h1 {
        text-align: center;
        margin-top: 60px;
    }

    h1 sapn {
        cursor: pointer;
        font: bold 60px/70px 'STSong';
    }

    .el-carousel__item h3 {
        color: #475669;
        font-size: 14px;
        opacity: 0.75;
        line-height: 150px;
        margin: 0;
    }

    .block {
         800px;
        margin: auto;
    }



    .el-carousel__item:nth-child(2n) {
        background-color: #99a9bf;
    }

    .el-carousel__item:nth-child(2n+1) {
        background-color: #d3dce6;
    }
</style>

vue CarDetail.vue页面

<template>
    <div class="car-detail">
        <h1>详情</h1>
        <div v-if="car.msg">
            <h1>{{ car.msg }}</h1>
        </div>
        <div v-else-if="car.id">
            <img :src="car.img" alt="">
            <h2>{{ car.title }}</h2>
            <h3>{{ car.price }}</h3>
            <h3>{{ car.info }}</h3>
        </div>
    </div>
</template>

<script>
    export default {
        name: "CarDetail",
        data() {
            return {
                car: {}
            }
        },
        created() {
            //拿到路由传递来的car主键
            let pk = this.$route.query.pk || this.$route.params.pk;
            //主键不存在,就直接结束方法
            if (!pk) return false;
            console.log(pk);
            //主键存在才请求后台
            this.$axios({
                url: this.$settings.base_url + `/get_car/${pk}/`,
            }).then(response => {
                this.car = response.data
            }).catch(error => {
                console.log(error.response)
            })
        }
    }
</script>

<style scoped>

</style>

vue app.vue 页面

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

后端

django urls.py

from django.views.static import serve
from django.conf import settings
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^get_cars/$', views.get_cars),
    url(r'^get_car/(?P<pk>d+)/$', views.get_car),


    url(r'^media/(?P<path>.*)',serve,{'document_root':settings.MEDIA_ROOT})

]

django views.py

from django.shortcuts import render,redirect,HttpResponse
from django.http import JsonResponse
from . import models
from django.conf import settings
# Create your views here.
def get_cars(request,*args,**kwargs):
    # print(request.method)
    # return JsonResponse({'msg':'get ok'})
    car_query=models.Car.objects.values('id','title','img')
    car_list=list(car_query)
    for car in car_list:
        car['img']='%s%s%s'%('http://localhost:8000',settings.MEDIA_URL,str(car.get('img')))
    return JsonResponse(car_list,safe=False)

def get_car(request,*args,**kwargs):
    pk=kwargs.get('pk')
    car_obj=models.Car.objects.filter(pk=pk).values('id','title','img','price','info').first()
    print(car_obj)
    if car_obj:
        car_obj['img']='%s%s%s'%('http://localhost:8000',settings.MEDIA_URL,str(car_obj.get('img')))
        return JsonResponse(car_obj,json_dumps_params={'ensure_ascii':False})
    return JsonResponse({'msg':'数据不存在'})

django models.py

from django.db import models

# Create your models here.

class Car(models.Model):
    title=models.CharField(max_length=64)
    price=models.DecimalField(max_digits=11,decimal_places=2)
    img=models.ImageField(upload_to='car',default='defult.jpg')
    info=models.TextField()

    class Meta:
        db_table='old_boy_car' #修改数据库表名
        verbose_name='汽车'
        verbose_name_plural=verbose_name

    def __str__(self):
        return self.title

原文地址:https://www.cnblogs.com/zqfzqf/p/12081134.html