1220 Vue conjunction with the front and rear ends of Django

vue installation

## 环境

附带安装pnm

npm换源

脚手架 快速换源

## 项目创建

cd 存放项目的目录

vue create 项目名  ===> 需要安装的组件  babel  router vuex

## 配置项目启动

pycharm打开项目,配置npm启动

## 加载vue环境

main.js完成vue环境的加载,完成根组件的渲染加载route,vuex等环境加载 

## Vue的ajax插件安装

axios

​```
安装插件 (一定要在项目目录下)
    cnpm install axios
    
在main.js中配置:
    import axios from 'axios'
    Vue.prototype.$axios = axios
    
使用,就可以直接ajax的使用
​```

Vue front of the set

Distribution of the page

index.html是项目中的唯一页面

App.vue是根组件,里面只有5行代码 其中 <router-view/> 指定渲染了view中的文件

views文件夹是页面组件,定义了各种页面的组件,home.vue是主页组件
    主页中使用导航条的话需要在components文件夹中定义小组件,然后导入才能使用 import Nav from '../components/Nav',导入完毕还需要进行注册 components:{ Nav }

导航条是小组件,需要在components文件夹中定义,导航条上有什么:主页跳转以及汽车页面跳转,标签跳转的<router-link to="/"> 当你跳转的时候,需要定义路由跳转,在router文件夹中的index.js脚本文件添加跳转,添加跳转需要进行导入,导入views文件夹中的路由跳转之后的界面.import Car from '../views/Car'  const routes = [{path:'car',component:car'}

car界面中需要有汽车的图片信息,汽车的数据是从后端拿到的,这里使用created(){}声明周期钩子函数获取,获取后端的数据进行渲染,渲染的时候使用CarTag定义小组件,在car组件中父传子将数据输入子组件,CarTag进行获取数据然后渲染图片以及标题.

给每一个图片的定义跳转链接,跳转到的界面使用拼接 <router-link :to="`car/detail/${pk=car.id}`"> url,然后在index中定义路由的跳转,使用有名分组的方式 path: '/car/detail/:pk' 

然后定义详情页的页面组件 views文件夹中cardetail组件页面,在组件页面中通过钩子函数获取url中的pk值   (let pk= this.$route.query.pk || this.$route.params.pk;)

Replace the background data

使用django将数据动态的传输到前端vue组件中
创建django项目

css styles

display: block;   将标签变成块级标签
nth-child()     定制指定位置的标准样式,可以在循环多个中使用  
/*清除浮动*/
.warp:after {    display: block;    content: '';    clear: both;}
/*vw :屏幕宽度  vh 屏幕高度*/
        width: 100vw;
        height: 100vh;

Django configuration

Internationalization Configuration

international configuration settings file

// 报错信息的设置,中文的信息提示
LANGUAGE_CODE = 'zh-hans'
// 时区的设置  上海
TIME_ZONE = 'Asia/Shanghai'
// 数据库的时区设置,创建时间就不会使用默认的
USE_TZ = False

TODO comment

# TODO 这里是注释

axios plug-in installation

Ajax installation of plug-in Vue: axios

1.安装插件(一定要在项目目录下):
    cnpm install axios

2.在main.js 中配置
    import axios from 'axios'
    Vue.prototype.$axios = axios;

3.使用 在任何一个组件中发送ajax请求,获取数据库中的数据
    this.$axios({
        // 后端数据的接口地址
        url:'http://127.0.0.1:8000/cars/',
        // 请求方式
        method:'get',
    // 请求成功之后的回调函数
    }).then(response=>{
        this.cars = response.data;
    // 请求失败的回调函数
    }).catch(error=>{
        
    })

CORS cross-domain problem (same origin policy)

当前端的Vue向后端发送请求的时候,后端不知道发送过来的数据是不是正常的,所以对请求进行了限制,Django默认只会对同源请求做响应

同源:
    http协议相同,ip服务器地址形同,app应用端口相同
跨域:
    协议.IP地址.应用端口有一个不同,就是跨域
    
Django默认是同源策略,存在跨域问题

Deal with cross-domain question: cors plug

Django后台安装cors插件
    pip install django-cors-headers
    
插件参考地址:https://github.com/ottoyiu/django-cors-headers/
1.注册模块插件
    INSTALLED_APPS = [
    ...
    'corsheaders'
]
2.配置中间件
    MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware'
]
3.开启允许跨域
    CORS_ORIGIN_ALLOW_ALL = True

axios submit data to the background

Here the data may be transferred to the background in the url Django in two ways

            this.$axios({
                url:'http://127.0.0.1:8000/cars/',
                method:'get',
                params:{ //url拼接参数
                    a:1,
                    b:2
                    c:3
                },
                data:{ //数据包参数
                    x:10,
                    y:20
                }

Stitching parameters params:{}

任何请求都可以携带
    params:{ 
        a:1,
        b:2,
    }

Packet Parametersdata:{}

get请求是无法携带的
    data:{ 
        x:10,
        y:20
    }

Django data set

media related

New media folder

Then settings.pyset MEDIA_ROOT:

MEDIA_ROOT = os.path.join(BASE_DIR,'media')

Followed by urls.pyprovision of the relevant configuration in the media route:

from django.urls import path,re_path
from django.views.static import serve
from cnblog import settings

##media配置——配合settings中的MEDIA_ROOT的配置,就可以在浏览器的地址栏访问media文件夹及里面的文件了
re_path(r'media/(?P<path>.*)$',serve,{'document_root':settings.MEDIA_ROOT}),

This route has been set up above, we can go to access the corresponding file according to media files in a folder path in the address bar of the browser (Note that in order to ensure safety, by default, Django project files in each directory is not by the address bar to access).

Of course, we realize here is the file upload function, you need to save the file information to the database, models.pythe contents of the file are as follows:

Sign in using admin

The registration table to model the admin interface

from . import models
admin.site.register(models.Car)

Use admin management table data added

Front-end receiving data

In the automotive database connection url to access all the car information, return to the front end, the front end of axios accept and begin rendering data

def get_cars(request,*args,**kwargs):
    # 获取数据库所有的数据
    car_query = models.Car.objects.values('id','title','img')
    car_list = list(car_query)
    for car in car_list:
        # 拼接图片文件的http真实路径
        car['img'] = '%s%s%s' % ('http://localhost:8000',settings.MEDIA_URL,str(car.get('img')))
    # 返回给前端页面
    return JsonResponse(car_list,safe=False)
created(){
            // 完成ajax请求后台数据
            this.$axios({
                url:'http://127.0.0.1:8000/cars/',
                method:'get',
                params:{ //url拼接参数
                    a:1,
                    b:2,
                    c:3,
                },
                data:{ //数据包参数
                    x:10,
                    y:20,
                }
            }).then(response => {
                // console.log(response)
                this.cars = response.data;
            }).catch(error=>{
                console.log('异常',error.response)
            });
        }
    }

Front-end interface for rendering a single car

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

element plug-in installation

Vue placed ElementUi

1.安装插件(一定要在项目目录下):
    cnpm install element-ui
    
2.在main.js中配置
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css';
    Vue.use(ElementUI);

 3.使用
    赋值粘贴

Using bootstrap plugin

JQuery plug-in installation

cnpm install jquery

Installation bootstrap

cnpm install bootstrap@3

vue / cli 3 Configuration jQuery: disposed in vue.config.js (without, manual new project root directory)

const webpack = require("webpack");

module.exports = {
    configureWebpack: {
        plugins: [
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery",
                "window.jQuery": "jquery",
                Popper: ["popper.js", "default"]
            })
        ]
        }
};

vue / cli 3 Configuration BootStrap: disposed in the main.js

import "bootstrap"
import "bootstrap/dist/css/bootstrap.css"

Vue Code

main.js Code

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
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.css'


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

Guess you like

Origin www.cnblogs.com/fwzzz/p/12080758.html