目次
1.django プロジェクトを作成する
1. PyCharm を開いて Django プロジェクトを作成します
django-admin startproject demo
2. プロジェクトのルート ディレクトリに入り、プロジェクト バックエンドとしてアプリを作成します。
cd demo
python manage.py startapp backend //backend就是app名称
2.ジャンゴを設定する
1.作成したアプリ(バックエンド)にサブルート(urls.py)を作成する
2. 新しく作成された urls.py でインターフェイス ルーティングを構成します。
from django.conf.urls import url
from . import views
urlpatterns = [
url('all/', views.get),#'all/'是前端get对应路由 views.get是views中对应函数
]
3. app の下のルートを demo の下の urls.py に追加します
from django.conf.urls import url,include
urlpatterns = [
url(r'^', include('backend.urls')),
]
4. demo の下の settings.py にクロスドメイン アクセスを追加します。
# INSTALLED_APPS 和 MIDDLEWARE 两个配置项setting.py文件初始化应该就是存在的
# 所以我们只需要在配置里加上就可以了
INSTALLED_APPS = [
...
'backend',#app的名字
'corsheaders', # pip install django-cors-headers 这个是为了防止跨域,具体请另查资料,我这里就不赘述了。
# 'rest_framework', # pip install djangorestframework 方便我们写后端接口
...
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
...
]
CORS_ORIGIN_ALLOW_ALL = True
5. app の下の views.py にインターフェイス関数を記述します。
from django.http import JsonResponse
def get(request):
return JsonResponse({'name':'python'})
6.ジャンゴを実行します。
python manage.py runserver
3.Vue プロジェクトを作成する
1. フロントエンド ストレージ ディレクトリに入り、次を実行します。
vue-init webpack front//安装中把vue-router选上,我们须要它来做前端路由
2. front ディレクトリに入り、次を実行します。
npm install //安装vue所须要的node依赖
3. 必要なパッケージをインストールし、vue を実行します。
npm install
npm install --save axios vue-axios
npm run dev
4. axios を src/ の下の main.js にグローバルにインポートします。
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import VueAxios from 'vue-axios'
//应用axios插件
Vue.use(VueAxios, axios)
// 配置后端路由
axios.defaults.baseURL = 'http://127.0.0.1:8000'
//将axios挂在全局上
Vue.prototype.$axios = axios
//关闭vue自带提示
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
5. src/components に新しい test.vue を作成します この時点で、フロントエンド インターフェイスは次のようになります。
6. インターフェイスにリクエストを送信してデータを取得します (test.vue に記述)
<template>
<div>{
{name}}</div>
</template>
<script>
export default {
data(){
return{
name:''
}
},
methods:{
getData () {
this.$axios
.get('all/')
.then(response=> {
this.name=response.data.name
console.log(response.data)
})
},
},
mounted(){
this.getData()
}
}
</script>
7. src/router/index.js の下に書かれた vue のルーティングを構成します。
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import test from '@/components/test'
Vue.use(Router)
export default new Router({
// 启用history模式(默认为hash)
model: 'history',
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/test',
name: 'test',
component: test
}
]
})