Table of Contents
Task List
Create Task
Home Web Front-end Vue.js Building a full-stack application: Vue3+Django4 practical case

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

Sep 10, 2023 pm 02:30 PM
vue django Full stack application

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 id="Task-List">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 id="Create-Task">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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

See all articles