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
Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

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.

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 Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use