当前位置:网站首页>V-IF, V-for, list filtering and sorting, forced binding of class and style, and collection of form information
V-IF, V-for, list filtering and sorting, forced binding of class and style, and collection of form information
2022-07-22 15:36:00 【Delete your code in the middle of the night·】
v-if
<body>
<div id="app">
<p v-if="isShow"> A successful confession </p>
<p v-else> Failure in confession </p>
<hr>
<p v-show="isShow"> To marry him success </p>
<p v-show="!isShow"> The proposal failed </p>
<button @click="changeIsShow"> Switch </button>
</div>
<script src="../js/vue.js"></script>
<script>
new Vue({
el:'#app',
data:{
isShow:true
},
methods: {
changeIsShow(){
this.isShow = !this.isShow
}
},
})
</script>
</body>
vif and vshow What's the difference between conditional rendering ?
vif If the latter condition is true , The current element will render , That is to say, if the condition is false, the element does not exist in memory
vshow Whether the latter condition is true or false , Will render , That is to say, if the condition is false, the element still exists in memory , Just use css Hide the
vif and vshow According to different scenarios , Efficiency is different
If our switching frequency is very high ,vshow More appropriate , Because there is no need to render elements repeatedly , Memory does not need to be created and destroyed repeatedly
If our switching frequency is not high ,vif More appropriate , Because the memory consumption is relatively small , High efficiency
Later we will use component tags , Component creation has a lifecycle , If we use vif On the component label
The assumption is false , This component will not be created , There is no component object in memory
If you are using vshow On the component label , Then whether the condition is true or false , This component will be created , The life cycle will execute the corresponding hook
From input url enter , What happened to the completion of page rendering ?
1、dns analysis , The essence is to resolve the domain name into ip: port
2、tcp Establishing a connection Three handshakes
3、http Request to send a request message
4、 The background server returns a response message
5、 After the browser gets the response message , Parse rendering
html ---- domTree
css ---- cssTree
Generative domTree and cssTree Merge into renderTree Rendering
6、 Disconnect from the background Four waves
v-for
<body>
<div id="app">
<ul>
<!-- key Is a virtual dom Conduct diffing When comparing algorithms , The identity on which it depends
If this identifier can use a unique value, use a unique value , Try not to use subscripts
If it's just for checking , Then write index Subscript no problem
If it is to add, delete or modify , Then there may be a problem with subscribing
At worst, it will also lead to inefficiency -->
<li v-for="(person,index) in persons" :key="person.id">
{
{person.id}} --- {
{person.username}} --- {
{person.age}}
</li>
</ul>
</div>
<script src="../js/vue.js"></script>
<script>
new Vue({
el:'#app',
data(){
return {
persons:[
{id:1,username:'zhaoliying',age:35},
{id:2,username:'yangmi',age:36},
{id:3,username:'dilireba',age:30}
]
}
}
})
</script>
</body>
vue Process responsive data
vue How to monitor data changes and update pages ( Click the button to modify the first item )
1、 Modify the properties of objects in the array , Find that the page can be changed
2、 Directly modify the entire object in the array through the subscript of the array , Found that the page cannot be changed
3、 Call the array method to directly modify the entire object in the array , The discovery page can also be changed
reason :
Modify the properties of objects in the array , It's all modifiable , Because all the attributes of the object have been added get and set Method ( Responsive data ),
data Properties of all objects in , It's all responsive
Directly modify the entire object of the array by subscript , It cannot be displayed on the page , But the data did change , The subscript of the array does not get and setIt is also possible to modify the entire object through the array method , because vue Which rewrites some of the native methods of the array , Added the function of showing to the page
The difference between object data and array data response
<body>
<div id="app">
<ul>
<li v-for="(person, index) in persons" :key="person.id">
{
{person.id}} --- {
{person.username}} --- {
{person.age}}
</li>
</ul>
<button @click="update"> Click to modify the name of the first person </button>
</div>
<script src="../js/vue.js"></script>
<script>
new Vue({
el:"#app",
data(){
return {
persons:[
{id:1,username:'zhaoliying',age:35},
{id:2,username:'yangmi',age:36},
{id:3,username:'dilireba',age:30}
]
}
},
methods: {
update(){
// this.persons[0].username = 'yingbao'
// this.persons[0] = {id:1,username:'yingbao',age:35}
this.persons.splice(0,1,{id:1,username:'yingbao',age:35})
}
},
})
</script>
</body>
vue When processing data, the response is based on the following rules
For the object
Once we instantiate vm At instance time ,vue Internal data hijacking , hold
data All the object attributes ( Including deep level ), Add the getter and setter
Make every attribute responsive
So the first one succeeded
For arrays
The array response is modified 7 A way , Just use the following 7 One of the methods 、
Then it must be responsive , In fact, the essence is to add the function of modifying the page to these array methods
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
So the third kind can
List filtering
<body>
<div id="app">
<input type="text" v-model="keyword">
<ul>
<!-- Not recommended , Low efficiency -->
<!-- <li v-for="(person, index) in persons" :key="person.id" v-if="person.username.indexOf(keyword)!==-1">
{
{person.id}} --- {
{person.username}} --- {
{person.age}}
</li> -->
<li v-for="(person, index) in newPersons" :key="person.id">
{
{person.id}} --- {
{person.username}} --- {
{person.age}}
</li>
</ul>
</div>
<script src="../js/vue.js"></script>
<script>
new Vue({
el:"#app",
data(){
return {
persons:[
{id:1,username:'zhaoliying',age:35},
{id:2,username:'yangmi',age:36},
{id:3,username:'dilireba',age:30}
],
keyword:''
}
},
computed: {
newPersons(){
let {persons,keyword} = this
return persons.filter(item => item.username.indexOf(keyword) !== -1)
}
},
})
</script>
</body>
vfor and vif Can we use ? The answer is yes
vfor and vif When used at the same time , Whose priority is higher : The answer is vfor
But not recommended vfor and vif Use at the same time , because vfor There will be many elements in itself , Every element has an instruction v-if
vif Instructions need to be parsed , The process of parsing instructions is very performance consuming , In this way, the efficiency will be very low
The reason is that the efficiency is extremely lowterms of settlement :
Compute properties , We calculate the attributes to display the data , Calculate as a new array , During the presentation, we will not pull the relationship with the original array
In this case ,vfor Traverse directly traverse the calculated new array
Sort the list
<body>
<div id="app">
<input type="text" v-model="keyword">
<ul>
<!-- Not recommended , Low efficiency -->
<!-- <li v-for="(person, index) in persons" :key="person.id" v-if="person.username.indexOf(keyword)!==-1">
{
{person.id}} --- {
{person.username}} --- {
{person.age}}
</li> -->
<li v-for="(person, index) in newPersons" :key="person.id">
{
{person.id}} --- {
{person.username}} --- {
{person.age}}
</li>
</ul>
<!-- Event callback It can be a callback or a function call
When we do not add any parameters , It can be written as a callback
When we need to add parameters , It can be written as a function call , But we can't add this
-->
<button @click="changeFlag(0)"> Sort as is </button>
<button @click="sortFlag = 1"> In ascending order of age </button>
<button @click="sortFlag = 2"> In descending order of age </button>
</div>
<script src="../js/vue.js"></script>
<script>
new Vue({
el:"#app",
data(){
return {
persons:[
{id:1,username:'zhaoliying',age:35},
{id:2,username:'yangmi',age:36},
{id:3,username:'dilireba',age:30}
],
keyword:'',
sortFlag:0 // Design sorting flag data
}
},
computed: {
newPersons(){
let {persons,keyword,sortFlag} = this
let arr = persons.filter(item => item.username.indexOf(keyword) !== -1)
// if(sortFlag){
// if(sortFlag === 1){
// arr.sort((a,b) => {
// return a.age - b.age
// })
// }else{
// arr.sort((a,b) => {
// return b.age - a.age
// })
// }
// }
if (sortFlag) arr.sort((a,b) => sortFlag === 1? a.age - b.age : b.age - a.age)
return arr
}
},
methods: {
// If you write a function later , There is only one line of code inside the function
// Functions can be omitted
changeFlag(flag){
this.sortFlag = flag
}
},
})
</script>
</body>
Filtering and sorting of lists
List filtering :
1、 Collect keywords entered by users Need to design the data collected vmodel collect keyword
2、 The page no longer shows the original array , But according to the original array and keyword Calculated new array , Otherwise, you will encounter vfor and vif Use at the same time
3、 Replace the data displayed on the page with a new array
Sort the list ( Sort after filtering )
1、 To sort, you need to design sorting identification data sortFlag 0 Original sample 1 Ascending 2 Descending
2、 Add click event , Click on the three buttons, we only need to be responsible for the modification sortFlag data
3、sortFlag The change of is to cause the new filtered array to change ,sortFlag It has to be added to the calculation
4、 After filtering , Only according to sortFlag Value , Sort the filtered array
Force binding class and style
Force binding style class and style
class Dynamic binding :
1、 Class name is uncertain String form
2、 Class name determination , But I don't know which takes effect Objects form
3、 Several class names are valid Array form
style Dynamic binding
1、 The original must be written in the object , The style name remains unchanged , Style values are dynamic
2、 If the style name is illegal , To change to the small hump writing
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.classA{
font-size: 80px;
}
.classB{
color: hotpink;
}
.classC{
background-color: greenyellow;
}
.classD{
font-size: 30px;
}
</style>
</head>
<body>
<div id="app">
<!-- Force binding class -->
<!-- 1、 I don't know which class this element should be , Which class did the backstage give me back String usage -->
<p class="classD" :class="myClass" > I love you, zhaoliying </p>
<!-- 2、 I know which classes are on this element , But I don't know which will take effect Object writing -->
<p :class="{classA:isA,classB:isB}"> I love you, zhaoliying </p>
<!-- 3、 There are multiple classes in the element that take effect , Multiple classes are also returned in the background Array writing -->
<p :class="classArr"> I love you, zhaoliying </p>
<!-- Force binding style -->
<!-- Style attributes we know , The value is returned by the background Object writing -->
<p :style="{fontSize,color:myColor}"> I love you, zhaoliying </p>
<button @click="updateClass"> Click change style </button>
</div>
<script src="../js/vue.js"></script>
<script>
new Vue({
el:'#app',
data(){
return {
myClass:'classA',
isA:true,
isB:false,
classArr:['classA','classB','classC'],
fontSize:'100px',
myColor:'skyblue'
}
},
methods: {
updateClass(){
this.isA = !this.isA
this.isB = !this.isB
}
},
})
</script>
</body>
The binding of events is related
Event binding method
v-on It's just a complex way to bind events
@ Just short
1、 Callback writing
Callback does not need to add brackets , Write the function name directly , When a function is defined, the first formal parameter receives the event object
2、 Function call
Function calls are called with brackets , When called ,vue A function will be automatically added to the outer layer of the function call we write , This function is the real callback
By default, this function has a formal parameter called $event,( Can't change ), If the function call we are writing needs to pass the event object , Then you have to pass the arguments
$event, Our function definition needs to receive this parameter , Get the event object to use , If you don't need it, you don't have to pass it , There is no event object in the function . If we pass parameters, we need not only event objects , You also need to define your own parameters , So at this time , You need to call the function , Pass on two , One is
$event, One is your own parameter$event Later we call it default parameter , In a native dom In the event, just see $event, Represents the event object
<body>
<div id="app">
<!-- The most primitive way of writing , And without parameters -->
<button v-on:click="test">test</button>
<!-- Abbreviate the most primitive way -->
<button @click="test">test</button>
<!-- By default, the callback we write passes a parameter, which is the event object
It is written in the same way as the following , Function call if you also want to get the event object
Because the outer layer automatically adds a function to you , The outer function becomes a callback function , The inner function wants to use
Event object , The event object that needs to be received by the outer function , Carry out manual transmission ,$event Can only appear in the template
Later we put $event It is called default parameter
-->
<button @click="test1($event)">test1</button>
<!-- Once the function call is written , And also pass the event object
The whole writing should be like this
Don't add... When writing function calls this, added this Just report a mistake , because this The direction has changed
function($event){
test1($event)
}
-->
<!-- You want to pass not only the event object, but also your own additional parameters , Then pass it together , There is no order , Pay attention when receiving -->
<button @click="test2(10,$event)">test2</button>
</div>
<script src="../js/vue.js"></script>
<script>
new Vue({
el:'#app',
data(){
return {
}
},
methods: {
test(event){
console.log(event.target.innerHTML);
},
test1(event){
console.log(event.target.innerHTML);
},
test2(num,event){
console.log(event.target.innerHTML,num);
}
},
})
</script>
</body>
Automatically collect forms
Automatically collect form data v-model Application
Input box data The input data will be automatically assigned to data The data of
Radio box data Selected value The value will be automatically paid data The data of
Multi box data The single use operation is Boolean Multiple use operations are value value
Pull down menu data Selected option Of value The value is automatically assigned to data The data of
Text field data The written text will be automatically assigned to data The data of
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 1、 Collect data of form elements , It's using v-model
2、 The general default is v-model What is collected is the form element value value
-->
<!-- Text input box and password input box ,value Value is the data entered by the user -->
user name : <input type="text" placeholder=" Please enter a user name " v-model="userInfo.username"> <br>
The secret code : <input type="password" placeholder=" Please input a password " v-model="userInfo.password"><br>
sex other :
<!-- Radio input box , The default is No value value ,value The value must be written by yourself -->
<label><input type="radio" name="sex" value="male" v-model="userInfo.gender"> male </label>
<label><input type="radio" name="sex" value="female" v-model="userInfo.gender"> Woman </label> <br>
Love good :
<!-- The multi selection input box is divided into group use and single use , Now this hobby belongs to group use
If it is used in groups , collect value Values need to be collected into an array , When used in groups value Values also need to be written by yourself -->
<label><input type="checkbox" value="basketball" v-model="userInfo.favs"></label>
<label><input type="checkbox" value="football" v-model="userInfo.favs"></label>
<label><input type="checkbox" value="ping-pang" v-model="userInfo.favs"></label> <br>
city City :
<!-- The data collected by drop-down selection is select To collect , in other words vmodel To write in select On the body
however select There is no value value ,select The collection is selected option Of value value
option Of value What is worth writing , It depends on what you collect ?
key:diffing The algorithm compares virtual dom Identification used
-->
<select v-model="userInfo.cityId">
<option :value="city.id" v-for="(city, index) in cities" :key="city.id">
{
{city.name}}
</option>
</select> <br>
Personal profile :
<!-- The text field is the same as the text input box -->
<textarea cols="30" rows="10" v-model="userInfo.desc"></textarea>
<br>
<!-- If multiple check boxes are used individually vmodel It can be understood as the default and checked The binding of -->
<input type="checkbox" v-model="userInfo.isChecked"> Agree to the agreement
<button @click="submit"> Submit </button>
</div>
<script src="../js/vue.js"></script>
<script>
new Vue({
el:'#app',
data(){
return {
userInfo:{
username:'',
password:'',
gender:'',
favs:[],
cityId:2,
desc:'',
isChecked:false
},
cities:[
{id:1,name:' Xi'an '},
{id:2,name:' Beijing '},
{id:3,name:' Shanghai '},
]
}
},
methods: {
// submit(){
// axios({
// url:'./xxx',
// method:'post',
// data:this.userInfo
// })
// }
},
})
</script>
</body>
</html>
边栏推荐
- [07] function call: why does stack overflow happen?
- JS advanced ES6 implementation inheritance
- [06] instruction jump: it turns out that if... Else is goto
- ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or
- The cluster planned in tidb includes 6 dB, 3 PD and 3 kV. When the application is disconnected, which address is it connected to?
- Autocomplete (autocomplete)
- LeetCode 0128.最长连续序列
- FPGA image processing learning face recognition
- Values swxxdp calculation in Res
- RuntimeWarning: Glyph 25152 missing from current font. font. set_ text(s, 0.0, flags=flags)
猜你喜欢
【FiddlerTX插件】使用Fiddler抓包腾讯课堂视频下载
加快标准体系建设,促进数据安全产业高质量发展
JMeter notes 1 | introduction and architecture of JMeter
df.describe() 详解+用法+示例
Rebound shell carries out suid authorization through ordinary users
A simple inventory management system source code
Seaborn barplot drawing summary
3d点云txt文件中删减nan点
A Recommendation for interface-based programming
cookie和session
随机推荐
Cloud native
码蹄集 - MT2201 · 各位之和
旋转矩阵_百度百科
海康、大华、宇视拉实时流url规则总结
[C language - program compilation] how does the line by line code get to an executable program step by step?
ROS学习(28)Web GUI
[07] function call: why does stack overflow happen?
Summary of URL rules for real-time streaming of Hikvision, Dahua and yushila
Leetcode exercise 1 - binary tree pruning
如何用一手数据可视化获得老板的青睐,抓住数据可视化关键点
Aidl example
【华为机试真题】组成最大数【2022 Q3 | 100分】
AI chief architect 11 - "3d+ai" application and expansion in smart Sports
Golang language cli Library
How to use first-hand data visualization to win the favor of the boss and grasp the key points of data visualization
v-if、v-for、列表的过滤与排序、强制绑定class和style、收集表单信息
MySQL (28) - transaction related
Can Oracle RAC be built on Youxuan database?
LeetCode练习1——二叉树剪枝
Bannertext (watermark text)