Vue.js Tutorial column today introduces the third part of Vue.js learning, 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.
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(); });
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.
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>
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 !== '' && 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 > 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:
Member: used to specify the element container corresponding to the Vue instance using a CSS selector. Here, I specify <p id="app" >
Element.
Members: used to set the data bound in the page. The following three data variables are set here:
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.
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>
需要注意的是,该引用标签在 HTML 页面中的位置必须要在自定义 JavaScript 脚本文件(即main.js
)的引用标签之前。当然,我在上述代码中只展示了axios.get
和axios.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!