Home > Web Front-end > Vue.js > Building a full-stack application: Vue3+Django4 practical case

Building a full-stack application: Vue3+Django4 practical case

王林
Release: 2023-09-10 14:30:11
Original
1399 people have browsed it

Building a full-stack application: Vue3+Django4 practical case

Building full-stack applications: Vue3 Django4 practical case

Introduction:
With the development of mobile Internet, full-stack development has attracted more and more attention. Full-stack development engineers can independently complete front-end and back-end development to improve development efficiency. In this article, we will introduce how to use the latest Vue3 and Django4 to build a full-stack application, and provide a practical case.

1. Introduction to Vue3 framework
Vue3 is one of the most popular front-end frameworks at present. It adopts a new API style called "combined API" to make the code more readable and maintainable. . Vue3 also introduces some new features, such as Teleport, Suspense, Fragment, etc., making the development experience richer.

Before writing a Vue3 application, we first need to install and configure the Vue3 development environment. We can use npm or yarn to install Vue3:

$ npm install -g @vue/cli
Copy after login

2. Introduction to Django framework
Django is an efficient, flexible and safe Python web development framework. It provides a complete set of tools for processing web requests, Components for accessing databases, processing forms, etc. Building complex web applications is easy with Django.

In order to use the latest Django4, we first need to install Python and Django. We can use the pip command to install Django:

$ pip install Django
Copy after login

3. Build a full-stack application
Now, we are ready to build a full-stack application. We will use Vue3 as the front-end framework and Django as the back-end framework to build a simple task management application.

  1. Create Django project
    First, we need to create a Django project. Open a command line window and run the following command:
$ django-admin startproject task_manager
Copy after login

This command will create a Django project named task_manager in the current directory.

  1. Create a Django application
    Next, we need to create an application in the Django project. Run the following command on the command line:
$ cd task_manager
$ python manage.py startapp tasks
Copy after login

This command will create an application named tasks in the Django project.

  1. Define database model
    In the Django project, we need to define a database model to store task data. Open the tasks/models.py file and add the following code:
from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
Copy after login

This will define a model named Task, which contains the title, description and creation time of the task.

  1. Create API View
    Next, we need to create the view function for handling API requests. Open the tasks/views.py file and add the following code:
from rest_framework.decorators import api_view
from rest_framework.response import Response

from .models import Task
from .serializers import TaskSerializer

@api_view(['GET', 'POST'])
def task_list(request):
    if request.method == 'GET':
        tasks = Task.objects.all()
        serializer = TaskSerializer(tasks, many=True)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = TaskSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)
Copy after login

This will define a view function named tasks_list for handling GET and POST requests. GET request returns a list of all tasks, while POST request is used to create new tasks.

  1. Create API serializer
    In the Django project, we need to create a serializer to serialize and deserialize data. The serializer is responsible for converting the database model into data in JSON format, and converting JSON data into the database model. Create a file named serializers.py in the tasks directory and add the following code:
from rest_framework import serializers

from .models import Task

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ['id', 'title', 'description', 'created_at']
Copy after login

This will define a serializer named TaskSerializer for serializing and decoding the Task model. Serialization.

  1. Configure URL routing
    Finally, we need to configure URL routing to map the API view to a specific URL. Open the task_manager/urls.py file and add the following code:
from django.urls import path

from tasks.views import task_list

urlpatterns = [
    path('api/tasks/', task_list, name='task-list'),
]
Copy after login

This will configure a URL route named task-list, which maps the task_list view function to the /api/tasks/ path.

4. Build Vue3 application
Now that we have completed the back-end construction, we will use Vue3 to build the front-end page.

  1. Create Vue3 project
    First, we need to create a Vue3 project. Run the following command in the command line:
$ vue create task-manager
Copy after login

This command will create a Vue3 project named task-manager.

  1. Install dependent modules
    After creating the project, we need to install some dependent modules. Run the following command in the command line:
$ cd task-manager
$ npm install axios
Copy after login

axios is a powerful HTTP client for sending asynchronous requests. We will use axios to communicate with the Django backend.

  1. Writing Vue components
    Then, we need to write some Vue components to display the task list and create an interface for new tasks. Open the TaskList.vue file in the src/components directory and add the following code:
<template>
  <div>
    <h1>Task List</h1>
    <ul>
      <li v-for="task in tasks" :key="task.id">
        {{ task.title }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tasks: []
    }
  },
  mounted() {
    this.fetchTasks()
  },
  methods: {
    async fetchTasks() {
      const response = await this.$http.get('/api/tasks/')
      this.tasks = response.data
    }
  }
}
</script>
Copy after login

This will define a Vue component named TaskList for displaying the task list.

Then, create a file named CreateTask.vue and add the following code:

<template>
  <div>
    <h1>Create Task</h1>
    <input type="text" v-model="title" placeholder="Title">
    <input type="text" v-model="description" placeholder="Description">
    <button @click="createTask">Create</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: '',
      description: ''
    }
  },
  methods: {
    async createTask() {
      const data = {
        title: this.title,
        description: this.description
      }
      await this.$http.post('/api/tasks/', data)
      this.title = ''
      this.description = ''
      this.$emit('task-created')
    }
  }
}
</script>
Copy after login

This will define a Vue component named CreateTask for creating new tasks.

  1. Modify the App component
    Finally, we need to modify the App.vue component and add the TaskList and CreateTask components to the page. Open the src/App.vue file and modify the following code:
<template>
  <div>
    <task-list @task-created="fetchTasks" />
    <create-task @task-created="fetchTasks" />
  </div>
</template>

<script>
import TaskList from './components/TaskList.vue'
import CreateTask from './components/CreateTask.vue'

export default {
  components: {
    TaskList,
    CreateTask
  },
  methods: {
    fetchTasks() {
      this.$refs.taskList.fetchTasks()
    }
  }
}
</script>
Copy after login

This will make the TaskList and CreateTask components display normally in the App page, and the fetchTasks method will be triggered when the task is created.

5. Run the application
Now that we have completed the front-end and back-end development work, we can run the application for testing.

  1. 启动Django后端
    在命令行中运行以下命令,启动Django后端服务器:
$ cd task_manager
$ python manage.py runserver
Copy after login
  1. 启动Vue3前端
    在一个新的命令行窗口中运行以下命令,启动Vue3前端服务器:
$ cd task-manager
$ npm run serve
Copy after login
  1. 测试应用
    现在,打开浏览器,访问http://localhost:8080,就可以看到应用的界面了。在任务列表中,可以看到已经创建的任务,点击“Create Task”按钮,可以创建新的任务。

结束语:
通过本文的介绍,我们了解了如何使用Vue3和Django4构建全栈应用的基本步骤。通过实战案例,我们学习了如何在Vue3中发送请求,并在Django中处理请求数据。希望本文对您的全栈开发学习之路有所帮助。

The above is the detailed content of Building a full-stack application: Vue3+Django4 practical case. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template