django+vue快速入门1
在这个快速入门中,我们将使用Django作为后端框架和Vue.js作为前端框架创建一个简单的CRUD(创建、读取、更新、删除)应用程序。
后端(Django):
- 创建一个新的Django项目:
django-admin startproject crudapi
- 创建一个新的应用:
python manage.py startapp crudapp
- 配置
models.py
以创建数据库模型:
# crudapp/models.py
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
- 迁移数据库:
python manage.py makemigrations
python manage.py migrate
- 创建一个序列化器:
# crudapp/serializers.py
from rest_framework import serializers
from .models import Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = '__all__'
- 创建一个视图:
# crudapp/views.py
from rest_framework import viewsets
from .models import Item
from .serializers import ItemSerializer
class ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
- 配置路由:
# crudapi/urls.py
from django.urls import include, path
from rest_framework import routers
from crudapp.views import ItemViewSet
router = routers.DefaultRouter()
router.register(r'items', ItemViewSet)
urlpatterns = [
path('', include(router.urls)),
]
前端(Vue.js):
- 创建一个新的Vue项目(可以使用Vue CLI):
vue create crudapp-frontend
- 安装axios:
npm install axios
- 创建Vue组件:
<!-- crudapp-frontend/src/components/ItemList.vue -->
<template>
<div>
<h1>Items</h1>
<ul>
<li v-for="item in items" :key="item.id">
{{ item.name }} - {{ item.description }}
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
items: []
};
},
created() {
this.fetchItems();
},
methods: {
fetchItems() {
axios.get('http://localhost:8000/items/')
.then(response => {
this.items = response.data;
})
.catch(error => {
console.error('There was an error!', error);
});
}
}
};
</script>
- 配置Vue路由和创建一个新的组件:
评论已关闭