Vue.js Tutorial column introduces the data-driven development of Vue.js learning part two.
In the Vue.js framework, the way to interact with HTML page elements is not as direct as the native JavaScript interface. It is first embedded in a series of similar HTML element tags. Bind data to the Vue directive attributes of ordinary tag attributes, and then modify the display mode and content of page elements by modifying these bound data in JavaScript code. In terms of programming methods, we usually call this way of using changes in data content to drive the business operations of the entire program "Data-driven development". This part of the notes will record how to use data-driven development methods to complete data binding and event response to achieve basic functions such as controlling page elements and CSS styles.
Data Binding
In the previous 01_sayHello
program, we now bind a name using template syntax in the <h1></h1>
tag For the data of sayHello
, this template syntax is actually the syntactic sugar of the v-text
instruction. In other words, the more standardized syntax of the <h1></h1>
tag should be:
<h1 v-text="sayHello"></h1>
Considering our traditional habit of writing HTML tags, use {{ data_name }}
Such template tags will be more comfortable. Of course, the v-text
directive sets the text content under the current element label. If you want to bind data to the attribute of the label itself, you have to use the v-bind
directive. The specific syntax is to add the v-bind:
prefix in front of the label attribute name to be set. For example, if you want to bind data to the src
attribute of the <img src="/static/imghwm/default1.png" data-src="vueLogo" class="lazy" alt="Vue.js Learning 2: Data-Driven Development" >
tag, you can do this:
<img src="/static/imghwm/default1.png" data-src="vueLogo" class="lazy" v-bind: style="max-width:90%" alt="Vue.js Learning 2: Data-Driven Development" >
Also, v-bind# The ## directive also has an abbreviated form. You only need to add a
: prefix before the label attribute name to which data is bound. In the previous
01_sayHello program, I used this form. After binding the data on the page element, you can create a Vue instance in the corresponding JavaScript script. This is the
main.js file I used in the
01_sayHello program. content written in. At least the following two members must be defined in this Vue instance object:
-
el
Member
: This member is used to set the element container corresponding to the current Vue instance. , which is usually aelement. In some cases, it can also be the
,
-
data
Member
: This member is used to set the data bound in the page element. Its value itself is also an object in JSON format. Each of the objects Each member corresponds to an object bound in a page element. For example, in the previous 01_sayHelloprogram, I bound the two data
sayHelloand
vueLogo, You must set corresponding values for them in the
datamember of the Vue object.
01_sayHello program is currently only a one-way data display business. If you want to make it interactive, you also need to bind events to page elements. In the Vue.js framework, to bind an event, you must first register an event handler for the target element tag through the
v-on directive. For example, if we want to use a button in the
01_sayHello program To control whether the
element is displayed or not, you can modify the
index.htm code of the program as follows:
Here, I mainly did the following Modification:你好,Vue.js
{{ sayHello }}
![]()
- First of all, a
- v-show
directive is added to the
tag, which can be used to bind a Boolean type Data (that is,
isShowhere) to determine whether to display the label where it is located.
Then, a new button label is added to the page, and the - v-bind
directive is used to set the
valueattribute of the label. The value of this attribute is a condition An expression that will display different text based on the value of
isShow.
Finally, use the - v-on
command (
@is the abbreviation of the
v-on:prefix of the command) for the new button The label registers a click event handler named
toggleShow.
main.js, as follows:
const app = new Vue({ el: '#app', data:{ sayHello: '你好,Vue.js!', vueLogo: 'img/logo.png', isShow: true }, methods:{ toggleShow: function() { this.isShow = !this.isShow; } } });Here, I mainly made the following modifications:
- 首先,在 Vue 对象的
data
成员中定义了之前绑定的布尔类型数据isShow
,并将其默认值设置为 true。 - 然后,为 Vue 对象新增了一个名为
methods
的成员。该成员用于设置页面元素中注册的事件处理函数,它的值也是一个 JSON 格式的对象。该对象的每个成员都对应一个已在页面元素中用v-on
指令注册的事件处理函数。在这里就是toggleShow
,该函数每次调用都会将isShow
的值取反。
这样一来,当我们在 Web 浏览器中打开该应用程序就会看到之前的 Vue 图标旁边多了个文本内容为隐藏
的按钮。当按钮被单击之后,图标就会消失,按钮上的文本也变成显示。之后,如果该按钮再次被单击,一切又会恢复原状。
用户输入
对于用户来说,除了触发事件之外,允许用户在运行时输入具体的数据也是一个应用程序必不可少的一项功能。下面将通过编写一个"待办事项"的程序来学习如何使用 Vue.js 框架实现能处理用户输入数据的应用程序界面。为此,我需要在code
目录下创建一个名为02_toDoList
的目录,并在该目录中创建一个名为index.htm
的文件,其代码如下:
<!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" ></script> <script defer="defer" src="js/main.js"></script> <title>待办事项</title> </head> <body> <p id="app"> <h1 id="待办事项">待办事项</h1> <p id="todo"> <ul> <li v-for="( task,index ) in taskList"> <input type="checkbox" v-model="doneList" :value="task"> <label :for="task">{{ task }}</label> <input type="button" value="删除" @click="remove(index)"> </li> </ul> </p> <p id="done" v-if="doneList.length > 0"> <h2 id="已完成事项">已完成事项</h2> <ul> <li v-for="task in doneList"> <label :for="task">{{ task }}</label> </li> </ul> </p> <input type="text" v-model="newTask" @keyup.enter="addNew"> <input type="button" value="添加新任务" @click="addNew"> </p> </body> </html>
接下来,我会在同一目录下再创建一个名为js
的目录,并在该目录下创建main.js
脚本文件,其代码如下:
// 程序名称: toDoList // 实现目标: // 1. 学习 v-model、v-for 等指令 // 2. 掌握如何处理用户输入 const app = new Vue({ el: '#app', data:{ newTask: '', taskList: [], doneList: [] }, methods:{ addNew: function() { if(this.newTask !== '') { this.taskList.push(this.newTask); this.newTask = ''; } }, remove: function(index) { if(index >= 0) { this.taskList.splice(index,1); } } } });
下面来具体分析一下这个程序。在通常情况下,Web 应用程序在前端接受用户输入信息的方式主要有两种:第一种方式是用文本框元素来获取用户从键盘输入的信息。在 Vue.js 框架中,我们可以用v-model
指令将<input type="text">
标签绑定到newTask
数据中,该指令与v-bind
指令不同的在于,它是一种双向绑定。也就是说,v-model
指令不止可以让 JavaScript 代码中对绑定数据的修改反映到页面元素中,也可以让页面元素获取到的用户输入数据同步到 JavaScript 代码中。在 JavaScript 代码获取到文本框中的用户输入内容之后,我们就可以通过事件处理函数addNew
将其加入到一个名为taskList
的数据列表中,然后将该事件处理函数注册给输入回车和鼠标单击事件。
第二种方式是用单选钮、复选框等选择性元素来获取用户用鼠标勾选的信息。例如在上面这个程序中,我在<p id="todo"></p>
元素中用v-for
指令创建了一系列<input type="checkbox">
,它们都提供v-model
指令将自己双向绑定到了另一个名为doneList
数据列表上。在 Vue.js 框架中,如果一组复选框元素被v-model
指令绑定到了一个列表类型的数据上,那么当这些复选框被选上时,它们的value
属性值就会被自动添加到这个被绑定的数据列表中。
为了证明被选中的复选框被加入到了doneList
数据列表中,我还在页面中添加了一个<p id="done"></p>
元素,并对doneList
数据列表进行了遍历显示。需要说明的是,用于遍历数据列表的v-for
指令主要有两种形式:
-
When we only need to traverse the values in the list, we can write like this:
v-for="item in dataList"
, then the data list (Each item of data in dataList
) will be read one by one by the iterative variable (item
) during the traversal process. -
When we need to get the list value and its index in the list at the same time, we can write like this:
v-for="(item,index) in dataList"
, at this time, during the traversal process of the data list (dataList
), the value of each item of data will be read by theitem
variable, and the index of each item of data will beindex
Variable reading.
The last thing to note is that for the <p id="done"></p>
element itself, I used the v-if
directive, which The effect is basically the same as the previous v-show
instruction. The only difference is: the v-if
instruction will directly add or delete the element node where it is located on the DOM tree, while # The ##v-show command simply hides or displays the element through the
style attribute of the element where it is located. In terms of execution efficiency, the
v-show command is more efficient. Here, we set that when there is no data in the
doneList list, the program will directly remove the
element from the page, and vice versa. Add this element to the page. Let’s take a look at the effect of
02_toDoList program operation:
## More related free learning:javascript(Video)
The above is the detailed content of Vue.js Learning 2: Data-Driven Development. For more information, please follow other related articles on the PHP Chinese website!

WhentheVue.jsVirtualDOMdetectsachange,itupdatestheVirtualDOM,diffsit,andappliesminimalchangestotherealDOM.ThisprocessensureshighperformancebyavoidingunnecessaryDOMmanipulations.

Vue.js' VirtualDOM is both a mirror of the real DOM, and not exactly. 1. Create and update: Vue.js creates a VirtualDOM tree based on component definitions, and updates VirtualDOM first when the state changes. 2. Differences and patching: Comparison of old and new VirtualDOMs through diff operations, and apply only the minimum changes to the real DOM. 3. Efficiency: VirtualDOM allows batch updates, reduces direct DOM operations, and optimizes the rendering process. VirtualDOM is a strategic tool for Vue.js to optimize UI updates.

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor
