目录
2-2-1 axios安装 - npm install axios
一、前后端交互实现思路
1-1 前端思路
- 创建视图组件,在template内进行数据的渲染
- 使用axios发送请求到服务器域名地址 - 注意路由的拼接
- 从后端获取的数据从respons.data内进行获取
1-2 后端思路
- 解决指定路由的跨域问题
- 基于DRF获取request内获取前端传输数据,处理之后使用response进行返回
二、前端设计
2-1 默认数据设置
2-1-1 创建视图组件 DataTest.vue
<template> <div class="about"> <h1>This is DataTest</h1> {{d2}} <p v-for="d in d1"> {{d}} </p> <button @click="init">点击获取数据</button> </div> </template> <script> export default { data:function () { return{ d1:['默认列表数据1','默认列表数据2'], d2:'默认字符串', } } } </script> <style scoped> </style>
2-1-2 router.js 路由配置
import Vue from 'vue' import Router from 'vue-router' import Home from './views/Home.vue' Vue.use(Router) export default new Router({ mode: 'history', base: process.env.BASE_URL, routes: [ { path: '/', name: 'home', component: Home }, { path: '/about', name: 'about', // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "about" */ './views/About.vue') }, { path: '/DataTest', name: 'DataTest', component: () => import('./views/DataTest.vue') }, ] })
2-1-3 App.vue配置
2-2 使用axios获取数据
2-2-1 axios安装 - npm install axios
2-2-2 main.js配置axios
2-2-3 视图组件中使用axios
export default { data: function () {return {} }, // 绑定方法 methods: { init: function () { //this.$http 就是axios,同ajax用法相同 this.$http.request({ url:_this.$url+'course/', //请求的地址 method:'get', //请求的方式 }).then(function (response) { // 请求发送成功执行的函数逻辑 }).catch(function (response) { // 请求发送失败的执行函数逻辑 }) }, } }
<template> <div class="about"> <h1>This is DataTest</h1> {{d2}} <p v-for="d in d1"> {{d}} </p> <button @click="init">点击获取数据</button> </div> </template> <script> export default { data:function () { return{ d1:['默认列表数据1','默认列表数据2'], d2:'默认字符串', } }, methods:{ init:function () { // axios体内的this不是指代当前页面 let _this = this this.$http.request({ url:_this.$url+'DataTest/', method:'get', }).then(function (response) { _this.d1=response.data }).catch(function (response) { console.log(response) }) } } } </script> <style scoped> </style>
三、服务器端设计
3-1 路由设计
from django.conf.urls import url from django.contrib import admin from LearnOnline import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^DataTest/', views.DataTest.as_view()), ]
3-2 视图函数
from django.shortcuts import render # Create your views here. from rest_framework.views import APIView from rest_framework.response import Response class DataTest(APIView): def get(self, request, *args, **kwargs): return Response(['后台列表数据1', '后台列表数据2'])
3-3 跨域问题 - CORS
''' MyMiddle.py ''' from django.utils.deprecation import MiddlewareMixin class MyCorsMiddle(MiddlewareMixin): def process_response(self, request, response): response['Access-Control-Allow-Origin'] = '*' if request.method == 'OPTIONS': response['Access-Control-Allow-Headers'] = '*' return response