學習網站專案學習 - 基於Django 和 Vue的前後端資料互動
阿新 • • 發佈:2018-12-29
目錄
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