Home Web Front-end Vue.js Vue.js Learning 3: Data interaction with the server

Vue.js Learning 3: Data interaction with the server

Oct 14, 2020 pm 05:21 PM
vue.js

Vue.js Tutorial column today introduces the third part of Vue.js learning, data interaction with the server.

Vue.js Learning 3: Data interaction with the server

Obviously, the previous 02_toDoList has a fatal flaw. That is, its data only exists on the browser side. Once the user closes or reloads the page, all the data he previously added to the program will be lost, and everything will return to the initial state of the program. To solve this problem, the front-end of the web application needs to store the input data obtained on the back-end server at the appropriate time, and then retrieve the data from the server when needed. This part of the notes will record how to use the Vue.js framework to complete the interaction between the front-end and back-end of a web application. This time, I will also build a "guestbook" application to run through the entire learning process.

First you need to execute npm install express body-parser knex and npm install sqlite3@<specified version>## in the code directory. #Command, install the back-end components needed to create a Web service (it should be noted that the sqlite3 installed here must select the corresponding version according to the prompts after knex is installed). Next, create a directory named 03_Message in the code directory, and execute the npm init -y command in this directory to initialize it into a Node.js project. Here, the reason why the components required by the server are installed in the upper-level directory of the project directory is because I also need to install the front-end components in the project directory and open them to the browser for access, so before and after Components required for the terminal are best stored separately.

Now, I am going to create a web service based on the Express framework. The specific method is to create a server-side script file named

index.js in the code/03_Message directory, and enter the following code in it:

const path = require('path');
const express = require('express')
const bodyParser = require('body-parser');
const knex = require('knex');
const port = 8080;

// 创建服务器实例
const app = express();

// 配置 public 目录,将其开放给浏览器端
app.use('/', express.static(path.join(__dirname, 'public')));
// 配置 node_modules 目录,将其开放给浏览器端
app.use('/node_modules', express.static(path.join(__dirname, 'node_modules')));

//配置 body-parser 中间件,以便获取 POST 请求数据。
app.use(bodyParser.urlencoded({ extended : false}));
app.use(bodyParser.json());

// 创建数据库连接对象:
const appDB = knex({
    client: 'sqlite3', // 设置要连接的数据类型
    connection: {      // 设置数据库的链接参数
        filename: path.join(__dirname, 'data/database.sqlite')
    },
    debug: true,       // 设置是否开启 debug 模式,true 表示开启
    pool: {            // 设置数据库连接池的大小,默认为{min: 2, max: 10}
        min: 2,
        max: 7
    },
    useNullAsDefault: true
});

appDB.schema.hasTable('notes')  // 查看数据库中是否已经存在 notes 表
.then(function(exists) {
    if(exists == false) { // 如果 notes 表不存在就创建它
        appDB.schema.createTable('notes', function(table) {
            // 创建 notes 表:
            table.increments('uid').primary();// 将 uid 设置为自动增长的字段,并将其设为主键。
            table.string('userName');         // 将 userName 设置为字符串类型的字段。
            table.string('noteMessage');      // 将 notes 设置为字符串类型的字段。
    });
  }
})
.then(function() {
    // 请求路由
    // 设置网站首页
    app.get('/', function(req, res) {
        res.redirect('/index.htm');
    });

    // 响应前端获取数据的 GET 请求
    app.get('/data/get', function(req, res) {
        appDB('notes').select('*')
        .then(function(data) {
            console.log(data);
            res.status(200).send(data);
        }).catch(function() {
            res.status(404).send('找不到相关数据');
        });
    });

    // 响应前端删除数据的 POST 请求
    app.post('/data/delete', function(req, res) {
        appDB('notes').delete()
        .where('uid', '=', req.body['uid'])
        .catch(function() {
            res.status(404).send('删除数据失败');
        });
        res.send(200);
    });

    // 响应前端添加数据的 POST 请求
    app.post('/data/add', function(req, res) {
        console.log('post data');
        appDB('notes').insert(
            {
                userName : req.body['userName'],
                noteMessage : req.body['noteMessage']
            }
        ).catch(function() {
            res.status(404).send('添加数据失败');
        });
        res.send(200);
    });

    // 监听 8080 端口
    app.listen(port, function(){
        console.log(`访问 http://localhost:${port}/,按 Ctrl+C 终止服务!`);
    });
})
.catch(function() {
    // 断开数据库连接,并销毁 appDB 对象
    appDB.destroy();
});
Copy after login
Due to Vue The characteristics of the .js framework. In addition to obtaining the specified HTML and JavaScript files, the front-end needs the services provided by the back-end, which are mainly the addition, deletion, modification and query operations of the database. Therefore, in the above service, in addition to

public, node_modules In addition to the entire directory being open to browser access, it mainly provides a data query service based on GET requests, and two data addition and deletion operations based on POST requests.

Next, I can start building the front-end part. First, you need to execute the

npm install vue axios command in the code/03_Message directory to install the front-end components to be used next (this command will automatically generate a node_modules Directory, as mentioned above, the directory will be opened to the browser as a whole by the server-side script). Then, continue to create the public directory in the same directory, and create a file named index.htm in it, with the following code:

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script defer="defer" src="/node_modules/vue/dist/vue.js"></script>
    <script defer="defer" src="/node_modules/axios/dist/axios.js"></script>
    <script defer="defer" src="/js/main.js"></script>
    <title>留言本</title>
</head>
<body>
    <p id="app">
        <h1>留言本</h1>
        <p id="showNote" v-for="note in notes">
            <span>{{ note.userName }} 说:{{ note.noteMessage }} </span>
            <input type="button" value="删除" @click="remove(note.uid)">
        </p>
        <p id="addMessage">
            <h2>请留言:</h2>
            <label :for="userName">用户名:</label>
            <input type="text" v-model="userName">
            <br>
            <label :for="Message">写留言:</label>
            <input type="text" v-model="Message"></input>
            <input type="button" value="添加留言" @click="addNew">
        </p>
    </p>
</body>
</html>
Copy after login
This page is mainly It is divided into two parts. The first part will use the

v-for command to iteratively display the comments that have been added to the database based on the data in notes, and provide a Delete the button to delete the specified message (use the v-on directive to bind the click event handler function). The second part is an input interface for adding a message. The v-model command is used here to obtain the userName and that need to be entered by the user. Messagedata. Now, I need to create the corresponding Vue object instance. To do this, I will create another js directory under the public directory I just created, and create a directory named # in it. The custom front-end script file of ##main.js has the following code: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">// 程序名称: Message // 实现目标: //   1. 学习 axios 库的使用 //   2. 掌握如何与服务器进行数据交互 const app = new Vue({     el: '#app',     data:{         userName: '',         Message: '',         notes: []     },     created: function() {         that = this;         axios.get('/data/get')         .then(function(res) {             that.notes = res.data;         })         .catch(function(err) {             console.error(err);         });     },     methods:{         addNew: function() {             if(this.userName !== '' &amp;&amp; this.Message !== '') {                 that = this;                 axios.post('/data/add', {                     userName: that.userName,                     noteMessage: that.Message                 }).catch(function(err) {                     console.error(err);                 });                 this.Message = '';                 this.userName = '';                 axios.get('/data/get')                 .then(function(res) {                     that.notes = res.data;                 })                 .catch(function(err) {                     console.error(err);                 });             }         },         remove: function(id) {             if(uid &gt; 0) {                 that = this;                 axios.post('/data/delete', {                     uid : id                 }).catch(function(err) {                     console.error(err);                 });                 axios.get('/data/get')                 .then(function(res) {                     that.notes = res.data;                 })                 .catch(function(err) {                     console.error(err);                 });             }         }     } });</pre><div class="contentsignin">Copy after login</div></div>This Vue instance is similar to the one we created before, and is mainly composed of the following four members:

  • el

    Member: used to specify the element container corresponding to the Vue instance using a CSS selector. Here, I specify <p id="app" >Element.

  • data

    Members: used to set the data bound in the page. The following three data variables are set here:

      notes
    • : This is an array variable used to store the added message records.
    • userName
    • : This is a string variable used to obtain "username" data.
    • Message
    • : This is a string variable used to obtain "message" data.
  • created

    Member: used for initialization when the program is loaded. Here, I read the added message from the server. record and load it into the notes variable.

  • methods

    Members: used to define event processing functions bound in the page. The following two event processing functions are defined here: <ul> <li> <code>addNew:用于添加新的留言记录,并同步更新notes中的数据。

  • remove:用于删除指定的留言记录,并同步更新notes中的数据。

通常情况下,我们在 Vue.js 框架中会选择使用 axios 这样的第三方组件来处理发送请求和接收响应数据的工作,引入该组件的方式与引入 Vue.js 框架的方式是一样的,可以像上面一样先下载到本地,然后使用<script>标签引入,也可以使用 CDN 的方式直接使用<script>标签引入,像这样:

<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://unpkg.com/axios/dist/axios.js"></script>
<!-- 或者 -->
<!-- 生产环境版本,优化了文件大小和载入速度 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Copy after login

需要注意的是,该引用标签在 HTML 页面中的位置必须要在自定义 JavaScript 脚本文件(即main.js)的引用标签之前。当然,我在上述代码中只展示了axios.getaxios.post这两个最常用方法的基本用法,由于该组件支持返回 Promise 对象,所以我们可以采用then方法调用链来处理响应数据和异常状况。关于 axios 组件更多的使用方法,可以参考相关文档(http://www.axios-js.com/zh-cn/docs/)。

更多相关免费学习:javascript(视频)

The above is the detailed content of Vue.js Learning 3: Data interaction with the server. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

In-depth discussion of how vite parses .env files In-depth discussion of how vite parses .env files Jan 24, 2023 am 05:30 AM

When using the Vue framework to develop front-end projects, we will deploy multiple environments when deploying. Often the interface domain names called by development, testing and online environments are different. How can we make the distinction? That is using environment variables and patterns.

What is the difference between componentization and modularization in vue What is the difference between componentization and modularization in vue Dec 15, 2022 pm 12:54 PM

The difference between componentization and modularization: Modularization is divided from the perspective of code logic; it facilitates code layered development and ensures that the functions of each functional module are consistent. Componentization is planning from the perspective of UI interface; componentization of the front end facilitates the reuse of UI components.

Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Detailed graphic explanation of how to integrate the Ace code editor in a Vue project Apr 24, 2023 am 10:52 AM

Ace is an embeddable code editor written in JavaScript. It matches the functionality and performance of native editors like Sublime, Vim, and TextMate. It can be easily embedded into any web page and JavaScript application. Ace is maintained as the main editor for the Cloud9 IDE and is the successor to the Mozilla Skywriter (Bespin) project.

Practical combat: Develop a plug-in in vscode that supports vue files to jump to definitions Practical combat: Develop a plug-in in vscode that supports vue files to jump to definitions Nov 16, 2022 pm 08:43 PM

vscode itself supports Vue file components to jump to definitions, but the support is very weak. Under the configuration of vue-cli, we can write many flexible usages, which can improve our production efficiency. But it is these flexible writing methods that prevent the functions provided by vscode itself from supporting jumping to file definitions. In order to be compatible with these flexible writing methods and improve work efficiency, I wrote a vscode plug-in that supports Vue files to jump to definitions.

Let's talk in depth about reactive() in vue3 Let's talk in depth about reactive() in vue3 Jan 06, 2023 pm 09:21 PM

Foreword: In the development of vue3, reactive provides a method to implement responsive data. This is a frequently used API in daily development. In this article, the author will explore its internal operating mechanism.

Explore how to write unit tests in Vue3 Explore how to write unit tests in Vue3 Apr 25, 2023 pm 07:41 PM

Vue.js has become a very popular framework in front-end development today. As Vue.js continues to evolve, unit testing is becoming more and more important. Today we’ll explore how to write unit tests in Vue.js 3 and provide some best practices and common problems and solutions.

A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) A simple comparison of JSX syntax and template syntax in Vue (analysis of advantages and disadvantages) Mar 23, 2023 pm 07:53 PM

In Vue.js, developers can use two different syntaxes to create user interfaces: JSX syntax and template syntax. Both syntaxes have their own advantages and disadvantages. Let’s discuss their differences, advantages and disadvantages.

A brief analysis of how vue implements file slicing upload A brief analysis of how vue implements file slicing upload Mar 24, 2023 pm 07:40 PM

In the actual development project process, sometimes it is necessary to upload relatively large files, and then the upload will be relatively slow, so the background may require the front-end to upload file slices. It is very simple. For example, 1 A gigabyte file stream is cut into several small file streams, and then the interface is requested to deliver the small file streams respectively.

See all articles