How to perform vue.js data binding operation
This time I will show you how to perform vue.jsdata binding operation, what are the precautions for vue.js data binding operation, the following is a practical case, Let’s take a look.
Data binding
Responsive data binding system. After the binding is established, the DOM will be synchronized with the data, and there is no need to manually maintain the DOM. Make the code more concise and easy to understand and improve efficiency.
Data binding syntax
1. Text interpolation
{{ }}Mustache tag
<span>Hello {{ name }}</span>
data:{ name: 'vue' } == > Hello vue
Single interpolation
Changing the vm instance attribute value after the first assignment will not cause DOM changes
<span v-once="name">{{ name }}</span>
2. HTML attributes
Mustache tag {{ }}
<p v-bind:id="'id-'+id"></p>
Abbreviation:
<p :id="'id-'+id"></p>
3. Binding expression
The text content placed in the Mustache tag. In addition to directly outputting the attribute value, a binding expression can consist of a simple JavaScript expression and optionally one or more filters (regular expressions are not supported, if complex conversion is required , use filters or computed properties for processing).
{{ index + 1}} {{ index == 0 ? 'a' : 'b' }} {{name.split('').join('|') }} {{ var a = 1 }} //无效
4. Filter
vue.js allows adding optional filters after expressions, indicated by the pipe character "|".
{{ name | uppercase }} // Vue.js将name的值传入给uppercase这个内置的过滤器中(本质是一个函数),返回字符串的大写值。 {{ name | filterA | filterB }} //多个过滤器链式使用 {{ name | filterA arg1 arg2 }} //传入多个参数
At this time, filterA passes the value of name as the first parameter, and arg1 and arg2 as the second and third parameters into the filter function.
Finally the return value of the function is the output result. arg1 and arg2 can use expressions or add single quotes to directly pass in strings.
For example:
{{ name.split('') | limitBy 3 1 }} // ->u,e
The filter limitBy can accept two parameters. The first parameter is to set the number of displays. The second parameter is optional and refers to the array subscript of the starting element. .
The 10 built-in filters of vue.js (removed in Vue.js2.0)
capitalize: The first character of the string is converted to uppercase.
uppercase: Convert the string to uppercase.
lowercase: The string is converted to lowercase.
currency: The parameters are {String}[currency symbol], {Number}[decimal places], convert the number into currency symbol, and automatically add numerical section numbers.
{{ amount | currency '¥' 2 }} //若amount值为1000,则输出为¥1,000.00
pluralize: The parameters are {String}single,[double,triple], and the string is pluralized.
<p v-for="c in count">{{ c | pluralize 'item' }} {{ c | pliralize 'st' 'nd' 'rd' 'th' }} </p>
//输出结果: 1item 1st 2items 2nd 3items 3rd 4items 4th
json: The parameter is {Number}[indent] space indentation number, and the json object data is output into a string that conforms to the json format.
debounce: The incoming value must be a function, and the parameter is optional, which is {Number}[wait], which is the delay length. The effect is that the action will not be executed until n milliseconds after the function is called.
<input v-on:keyup="onKeyup | debounce 500"> //input元素上监听了keyup事件,并且延迟500ms触发
limitBy: The incoming value must be an array, the parameter is {Number}limit
, {Number}[offset]
, and the limit is Display the number, offset is the starting array subscript.
<p v-for="item in items | limitBy 10"></p> //items为数组,且只显示数组中的前十个元素
filterBy: The incoming value must be an array, and the parameter is {String | Function}targetStringOrFunction
, which is the string or function that needs to be matched; "in" can Select separator. {String}[...searchKeys]
, is the retrieved attribute area.
<p v-for="name in names | filterBy '1.0'">{{ name }}</p> //检索names数组中值包含1.0的元素 <p v-for="item in items | filterBy '1.0' in 'name'">{{ item | json }}</p> //检索items中元素属性name值为1.0的元素输出。检索区域也可以为数组,即in [name,version],在多个属性中进行检索。
//输出结果 vue1.0 {"name":"vue1.0","version":"1.0"}
Use a custom filter function, which can be defined in the options methods
<p v-for="item in items | filterBy customFilter" methods:{ cuestomFilter:function(item){ if(item.name) return true; //检索所有元素中包含name属性的元素 } }
orderBy: The incoming value must be an array, and the parameter is {String |Array|Function}sortKeys
, which specifies the sorting strategy.
Single key name:
<p v-for="item in items | orderBy 'name' -1">{{ item.name}}</p> //items数组中以键名name进行降序排列
Multiple key names:
<p v-for="item in items | orderBy [name,version]">{{item.name}}</p> //使用items里的两个键名进行排序
Custom sorting function:
<p v-for="item in items | orderBy customOrder">{{item.name}}</p> methods:{ customOrder: function(a,b){ return parseFloat(a.version) > parseFloat(b.version) //对比item中version的值的大小进行排序 } }
5. Command The value of the
directive is limited to the binding expression, that is, when the value of the expression changes, some special behavior will be applied to the bound DOM.
Parameter: src is the parameter
<img v-bind:src="avatar" /> <==> <img src="{{avatar}}" />
修饰符:以半角句号.开始的特殊后缀,用于表示指令应该以特殊方式绑定。
<button v-on:click.stop="doClick"></button> //stop:停止冒泡。相当于调用了e.stopPropagagation().
计算属性
避免在模板中加入过重的业务逻辑,保证模版的结构清晰和可维护性。
1.基础例子
var vm = new Vue({ el: '#app', data: { firstName:'Gavin', lastName:'CLY' }, computed: { fullName:function(){ //this指向vm实例 return this.firstName + ' ' + this.lastName; } } })
<p>{{ firstName }}</p> //Gavin <p>{{ lastName }}</p> //CLY <p>{{ fullName }}</p> //Gavin CLY
注:此时对vm.firstName
和vm.lastName
进行修改,始终会影响vm.fullName
。
2.Setter
更新属性时带来便利
var vm = new Vue({ el:'#el', data:{ cents:100 }, computed:{ price:{ set:function(newValue) { this.cents = newValue * 100; }, get:function(){ return (this.cents / 100).toFixed(2); } } } })
表单控件
v-model:对表单元素进行双向数据绑定,在修改表单元素值时,实例vm中对应的属性值也同时更新,反之亦然。
var vm = new Vue({ el:'#app', data: { message: '', gender: '', cheched: '', multiChecked: '', a: 'checked', b: 'checked' } })
1. Text
输入框示例,用户输入的内容和vm.message直接绑定:
<input type="text" v-model="message" /> <span>Your input is : {{ message }} </span>
2. Radio
单选框示例:
<label><input type="radio" value="male" v-model="gender">男</lable> <label><input type="radio" value="famale" v-model="gender">女</lable> <p>{{ gender }}</p> //显示的是value值
3.Checkbox
单个勾选框,v-model即为布尔值,此时Input的value并不影响v-model的值。
<input type="checkbox" v-model="checked" /> <span>checked: {{ checked }} </span> //显示的是true/false
多个勾选框,v-model使用相同的属性名称,且属性为数组。
<label><input type="checkbox" value="1" v-model="multiChecked">1</label> <label><input type="checkbox" value="1" v-model="multiChecked">2</label> <label><input type="checkbox" value="1" v-model="multiChecked">3</label> <p>MultiChecked:{{ multiChecked.join{'|'} }}</p> //multiChecked:1|2
4.Select
单选
<select v-model="selected"> <option selected>A</option> <option>B</option> <option>C</option> </select> <span>Selected: {{ selected }}</span>
多选
<select v-model="multiSelected" multiple> <option selected>A</option> <option>B</option> <option>C</option> </select> <span>MultiSelected: {{ multiSelected.join('|') }}</span>
5.绑定value
通过v-bind实现,表单控件的值绑定到Vue市里的动态属性上。
Checkbox
<input type="checkbox" v-model="checked" v-bind:true-value="a" v-bind:false-value="b" />
选中:
vm.checked == vm.a //=> true
未选中:
vm.checked == vm.b //=>true
Radio
<input type="radio" v-model="checked" v-bind:value="a" >
选中:
vm.checked == vm.a //=> true
3.Select Options
<select v-model="selected"> <!-- 对象字面量 --> <option v-bind:value="{ number:123}">123</option> </select>
选中:
typeof vm.selected //=> object vm.selected.number //=> 123
6.参数特性
.lazy:默认情况下,v-model在input事件中同步输入框与数据,加lazy属性后会在change事件中同步。
<!-- 在 "change" 而不是 "input" 事件中更新 --> <input v-model.lazy="msg" >
.number:自动将用户输入转为Number类型,如果原值转换结果为NaN,则返回原值。
<input v-model.number="age" type="number">
.trim:如果要自动过滤用户输入的首尾空格,可以添加 trim 修饰符到 v-model 上过滤输入
<input v-model.trim="msg">
Class与Style绑定
1.Class绑定
对象语法:v-bind:class
接受参数是一个对象,而且可以与普通的class属性共存。
<p class="tab" v-bind:class="{'active':active,'unactive':!active}"></p>
vm实例中需要包含:
data:{ active:true }
渲染结果为:
<p class="tab active"></p>
数组语法:v-bind:class
也接受数组作为参数。
<p v-bind:class="[classA,classB]"></p>
vm实例中需要包括:
data:{ classA:"class-a", classB:"class-b" }
渲染结果为:
<p class="class-a class-b"></p>
使用三元表达式切换数组中的class
<p v-bind:class="[classA,isB?classB:""]"></p>
若
vm.isB = false
则渲染结果为
<p class="class-a"></p>
2.内联样式绑定(style属性绑定)
对象语法:直接绑定符合样式格式的对象。
<p v-bind:style="alertStyle"></p>
vm实例中包含:
data:{ alertStyle:{ color: 'red', fontSize: '2px' } }
<p v-bind:style="{fontSize:alertStyle.fontSize,color:'red'}"></p>
数组语法:v-bind:style
允许将多个样式对象绑定到同一元素上。
<p v-bind:style="[ styleObjectA,styleObjectB]" .></p>
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to perform vue.js data binding operation. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).
