search
HomeWeb Front-endVue.jsVue.js Learning 3: Data interaction with the server

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 </specified>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();
});
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:

nbsp;html>


    <meta>
    <meta>
    <meta>
    <script></script>
    <script></script>
    <script></script>
    <title>留言本</title>


    <p>
        </p><h1 id="留言本">留言本</h1>
        <p>
            <span>{{ note.userName }} 说:{{ note.noteMessage }} </span>
            <input>
        </p>
        <p>
            </p><h2 id="请留言">请留言:</h2>
            <label>用户名:</label>
            <input>
            <br>
            <label>写留言:</label>
            <input>
            <input>
        
    

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: <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>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"></p>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></script>标签引入,也可以使用 CDN 的方式直接使用<script></script>标签引入,像这样:

<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script></script>
<!-- 或者 -->
<!-- 生产环境版本,优化了文件大小和载入速度 -->
<script></script>

需要注意的是,该引用标签在 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
This article is reproduced at:cnblogs. If there is any infringement, please contact admin@php.cn delete
The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

How to implement component jump for vueHow to implement component jump for vueApr 08, 2025 am 09:21 AM

There are the following methods to implement component jump in Vue: use router-link and <router-view> components to perform hyperlink jump, and specify the :to attribute as the target path. Use the <router-view> component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.

How to jump to the div of vueHow to jump to the div of vueApr 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

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft