笔记为自我总结整理的学习笔记,若有错误欢迎指出哟~
django 和 Vue.js 是一对非常强大的技术组合,可以用于构建现代化的 Web 应用程序。下面是对它们的简要介绍:
使用 Django 和 Vue.js 可以实现前后端分离的开发模式,使前端和后端的开发团队可以并行工作。你可以将 Django 用作后端 API 服务器,负责处理数据存储、用户认证等功能,而 Vue.js 则负责构建用户界面,并通过 AJAX 请求与后端 API 进行数据交互。
node -v # v18.18.2 npm -v # 9.8.1 vue --version # @vue/cli 4.5.13
vue create frontend (frontend 是项目名)

选择自定义:Manually select features
选择配置项:通过键盘上下键移动,使用空格键勾选,然后回车
( ) Babel // 代码编译 ( ) TypeScript // ts ( ) Progressive Web App (PWA) Support // 支持渐进式网页应用程序 ( ) Router // vue路由 ( ) Vuex // 状态管理模式 ( ) CSS Pre-processors // css预处理 ( ) Linter / Formatter // 代码风格、格式校验 ( ) Unit Testing // 单元测试 ( ) E2E Testing // 端对端测试
如果想要模板简洁,可以不添加Linter/Formatter和Unit Testing

选择VUE版本:3.x
第三方配置文件存在的方式:In dedicated config files
是否保存本次配置为预设项目模板:选择N
cd frontend
npm run serve

Element Plus是一套基于Vue 3.0的桌面端UI组件库,提供了丰富的UI组件和交互效果,使开发者能够更便捷地构建各种类型的Web应用程序。 Element Plus 是对 Element UI 的升级版本,在功能和性能上做了一些改进,并且支持 Vue 3.0。
npm install element-plus --save
报错则用:npm install element-plus --save -legacy-peer-deps
npm list element-plus 查看版本
element-plus@2.4.2

vue-router是Vue.js官方的路由管理器,它与Vue.js深度集成,用于构建单页面应用程序。通过vue-router,您可以实现页面之间的切换、导航以及路由参数的传递等功能。
npm install vue-router@4
npm list vue-router 查看版本
vue-router@4
axios是一个基于Promise的HTTP客户端,可以用在浏览器和Node.js环境中,它是Vue.js中常用的发送网络请求的工具。
npm install axios
npm list axios 查看版本
axios@1.6.2
pip install django== 2.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install django-cors-headers== 2.5.3 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install mysqlclient== 2.2.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
python --version # Python 3.9.18 django # 2.0 django-cors-headers #2.5.3 mysqlclient #2.2.0
activate pydjango
django-admin startproject backend
cd backend
python manage.py startapp myapp
conda虚拟环境pydjango

python manage.py runserver
CORS是Cross-Origin Resource Sharing(跨域资源共享)的缩写,是一种用于在Web应用程序中处理跨域请求的标准机制。当一个Web页面通过JavaScript发起对不同域(域名、端口或协议)的服务器资源的请求时,就会涉及到跨域请求。
当您的Vue.js前端应用程序请求访问Django后端时,如果二者位于不同的域名或端口上,就会触发跨域请求,此时可能会被浏览器拦截。
在Django项目中安装django-cors-headers库:
activate pydjango #django-cors-headers安装在哪个python环境下 pip install django-cors-headers -i https://pypi.tuna.tsinghua.edu.cn/simple
在Django项目的设置文件(settings.py)中添加corsheaders到INSTALLED_APPS中:
INSTALLED_APPS = [
    # ...
    'corsheaders',
    # ...
]
 在设置文件中的MIDDLEWARE列表中添加CorsMiddleware:
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # 添加这一行
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
 可以根据需求进行配置,例如允许的来源域列表、允许的HTTP方法等。以下是一个示例配置,允许所有源(*)的跨域请求:
CORS_ALLOW_ALL_ORIGINS = True
# 增加跨域忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
# 允许所有方法
CORS_ALLOW_METHODS = ('*')
# 允许所有请求头
CORS_ALLOW_HEADERS = ('*')
 或者,您可以设置允许的特定来源域列表:(我使用这个)
CORS_ALLOWED_ORIGINS = [
    'http://localhost:8080',  # Vue.js前端应用的地址
    'http://example.com',     # 其他允许的域名
]
 通过以上配置,django-cors-headers将会在Django后端中处理跨域请求,允许Vue.js前端应用程序与Django后端进行跨域通信。这样,您就可以在Vue.js应用中使用axios或其他HTTP客户端库发送请求到Django后端,并成功获取响应数据。
# setting.py
INSTALLED_APPS = [
	...
    'corsheaders',  #跨域add
    'myapp.apps.MyappConfig'    #注册app
]
 
# urls.py
from django.urls import path
from myapp import views
urlpatterns = [
    # path('admin/', admin.site.urls),
    path("index/", views.index),
]
 
# views.py
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
    return HttpResponse("欢迎使用!")
 
启动项目进行测试:

axios是一个基于Promise的HTTP客户端,可以用在浏览器和Node.js环境中,它是Vue.js中常用的发送网络请求的工具。
npm install axios
npm list axios 查看版本
axios@1.6.2
main.js 是 Vue.js 项目的主入口文件,负责创建 Vue 应用实例、设置全局配置,并将应用挂载到页面的特定元素上。同时也用于导入并配置其他必要的模块和库。
//main.js
import { createApp } from 'vue'
import App from './App.vue'
// 导入router
import router from './router.js';
// 导入axios
import axios from 'axios';
// 设置 axios 的全局配置
axios.defaults.baseURL = 'http://127.0.0.1:8000'; // 设置基础 URL
axios.defaults.headers.common['Authorization'] = 'Bearer token'; // 设置公共请求头
// createApp(App).mount('#app')
const app = createApp(App)
app.use(router)
// 将 axios 实例挂载到全局属性中
app.config.globalProperties.$http = axios;
app.mount('#app')
 
router.js 是 Vue Router 的配置文件,用于定义和配置应用的路由信息。导入了 vue-router 模块,定义了路由配置数组 routes,然后通过 createRouter 创建了路由实例,并最终导出该实例供其他地方使用。
//router.js
// 导入vue-router
import { createRouter, createWebHistory } from 'vue-router';
// 导入你的组件
import HelloWorld from './components/HelloWorld.vue';
const routes = [
  {
    path: '/',
    component: HelloWorld
  },
  {
    path: '/hello',
    component: HelloWorld
  }
  // 其他路由...
];
const router = createRouter({
  history: createWebHistory(),
  routes
});
export default router;
 
根组件App.vue。它是一个容器组件,用于承载整个应用的内容,并作为其他组件的父组件。
通过使用 
  
     
Vue 本身并不提供内置的 HTTP 客户端功能。通常情况下,这段代码应该依赖于一个名为 $http 的插件或库,比如 Axios。如果这里使用的是 Axios,那么 this.$http.get('/index') 就是通过 Axios 发起一个 GET 请求,请求的 URL 是 ‘/index’。这个请求会返回一个 Promise 对象,可以通过 .then() 方法处理请求成功的结果,或者通过 .catch() 方法处理请求失败的情况。
测试 
前端启动:进行跨域访问测试
