一、Django Vue index參數
在使用Django與Vue結合的時候,需要特別關注的是index參數。由於Vue是前端框架,因此我們需要在Django中指定我們要使用哪個index.html頁面。這個可以通過在settings.py文件中進行如下設置:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'libraries':{
'staticfiles': 'django.templatetags.static',
},
'builtins':[
'django.contrib.staticfiles.templatetags.staticfiles',
],
'string_if_invalid': 'Undefined',
'debug': True,
'loaders': [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
]),
],
'context_processors': [
'django.template.context_processors.request',
],
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media',
'django.template.context_processors.csrf',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.template.context_processors.i18n',
],
'debug': settings.DEBUG,
'loaders': [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
]),
],
},
},
},
]其中的DIRS參數需要設置為Vue項目打包後的dist文件夾,可以使用os.path.join()函數獲取。具體的代碼如下:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'path/to/dist')
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]二、Django Vue多頁面
如果需要使用Vue進行多頁面開發,需要在Django中進行多個路由設置。這可以通過修改url.py文件實現:
urlpatterns = patterns('',
url(r'^$', views.home_page, name="home"),
url(r'^about/$', views.about_page, name="about"),
url(r'^contact/$', views.contact_page, name="contact"),
)其中的views是Django中的視圖函數。如下所示:
def home_page(request):
return render(request, 'home.html', context={})
def about_page(request):
return render(request, 'about.html', context={})
def contact_page(request):
return render(request, 'contact.html', context={})而對應的Vue頁面則可以放在dist文件夾下的相應位置。
三、Django Vue教程
如果要學習Django和Vue的使用,推薦參考以下教程:
官方文檔:https://docs.djangoproject.com/en/3.2/
Vue.js教程:https://cn.vuejs.org/v2/guide/
這兩份教程可以講解Django和Vue的使用方法,建議您一邊學習一邊進行實踐。
四、Django Vue獲取前端屬性
獲取前端屬性可以在Vue的methods中進行定義,同時需要使用Axios庫和Django的request庫進行交互。具體代碼如下:
// 前端Vue代碼
import axios from 'axios';
export default {
name: 'test',
props: {
name: {
type: String,
default: ''
}
},
data () {
return {
message: ''
}
},
methods: {
submitMessage () {
var self = this;
axios.post('/api/submit-message', {
message: self.message
}).then(function (response) {
self.$emit('update');
}).catch(function (error) {
console.log(error);
});
}
}
}
# 後台Django代碼
from django.views import View
from django.http import JsonResponse
class SubmitMessageView(View):
def post(self, request):
message = request.POST.get('message')
# do something with the message
return JsonResponse({'status': 'success'})這樣前端就可以通過submitMessage()方法把message數據傳送給後台,並進行修改操作。
五、Django Vue前後端分離
前後端分離可以使用Django Rest Framework和Vue-Axios進行實現。具體代碼如下:
# 後端Django代碼
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
class TestApi(APIView):
permission_classes = [permissions.IsAuthenticated]
def get(self, request, format=None):
content = {
'status': 'success',
'data': ['hello', 'world']
}
return Response(content)
# 前台Vue代碼
import axios from 'axios';
export default {
name: 'test',
data () {
return {
messages: []
}
},
created () {
var self = this;
axios.get('/api/test').then(function (response) {
self.messages = response.data['data'];
}).catch(function (error) {
console.log(error);
});
}
}這樣前台就能夠通過axios獲取後台的數據,並進行展示。
六、Django Vue項目
要使用Django和Vue進行項目開發,可以參考以下步驟:
第一步:創建Django項目
$ django-admin.py startproject myproject
第二步:創建Vue項目
$ vue init webpack myproject-web $ cd myproject-web $ npm install axios
第三步:在Vue項目的src目錄中創建一個新的main.js文件,用於啟動Vue
// src/main.js
import Vue from 'vue'
import App from './App.vue'
import Axios from 'axios'
Vue.config.productionTip = false
Axios.defaults.baseURL = `http://localhost:8000/`
Vue.prototype.$http = Axios
new Vue({
render: h => h(App),
}).$mount('#app')
第四步:設置Django的STATICFILES_DIRS選項,指向Vue項目的dist目錄
# myproject/settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "myproject-web/dist")
]
第五步:創建Django的RESTful API
# myproject/views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def example_view(request):
return Response({'foo': 'bar'})
第六步:讓Django返回Vue的index.html文件
# myproject/views.py
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
這樣就能夠完成一個簡單的Django+Vue項目的開發。
七、Django Vue3模板
Django Vue3模板可以直接使用Django Vue官方提供的vue-cli-plugin-django命令行進行創建。具體命令如下:
$ vue create --default myapp $ cd myapp $ vue add django
這個過程會提示你設置Django項目的名稱和端口號,完成後就能夠開始開發Django Vue項目了。
八、Django Vue運維
對於Django Vue的運維,主要是需要注意以下幾個方面:
- 升級Django和Vue版本時需要注意兼容性
- 對於靜態資源的處理需要特別注意,可以使用CDN進行加速
- 需要遵守Vue和Django的開發規範,保證代碼可讀可維護
- 在部署時需要考慮服務器的配置和環境問題
以上就是Django與Vue的完美結合的介紹,希望能夠對您的Django Vue項目開發有所幫助。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/285017.html
微信掃一掃
支付寶掃一掃