Author: Ziksang, a mixed yuan thunderbolt player
After the release of Foundation 1, I really found that after further analysis of THE API and explanation of the actual demo at work, I got an average of one minute and one like early in the morning, which made me very happy. My efforts were not in vain, and I decided to attack immediately to build Foundation 2. In the basic part, I’m going to show you the list render V-for instruction, which I think is the core of the basic part, why I put it in the second part, because I have a lot of demo examples based on v-for instruction, which is the core of what we do, we take data from the background, we render data, If you are not very thorough about the basic 1 because of the V-for instruction, please look back at the basic 1 after this article, or the same sentence, support my creation please give a big like
praise
V-for list rendering
- V-for array Array rendering
We use the V-for instruction to render from an array of options. The V-for directive requires special syntax in the form of item in items, which is the source data array and item is the alias of the iteration of the array elements.
Application Scenarios: Usually, enter an activity to show all participated in the activities of the staff, there is a name, age, time signing up and so on, just for the three example, the background will return a collection arraylist array, each element in the set must be an object, that we how to put the array collection efficiency, reasonable rendering the page, , and then get the user ID and go to the next page to query the memberDetail. Those who have used JQ must have very complicated knowledge and generally must use the template engine like ArtTemplate
<template> <div> <ul> <li v-for="(item,index) in memberList" @click="memberDetail(index)"> <span>{{item.custName}}</span> <span>{{item.age}}</span> <span>{{item.joinTime}}</span> </li> </ul> </div> </template> <script> export default {created () {// This. MemberList = [{custName: "ziksang1",age:20,joinTime : "2014-01-02",custId:1}, {custName : "ziksang2",age:21,joinTime : "2014-01-03",custId:2}, {custName : "ziksang3",age:22,joinTime : "2014-01-04",custId:3}, {custName : "ziksang4",age:23,joinTime : "2014-01-05",custId:4}, ] }, data () { return { memberList : [] } }, methods : { memberDetail (index) { sessionStorage.custId = this.memberList[index].custId } } } </script>Copy the code
1. If you use data in the Template template, you must declare assignment in the data option. We give memberList a [] array 2. In the created function we just simulate the data we get from the background and assign it to the memberList in the data option, 3.(item,index) in memberList is a syntax that vue encapsulates. Item represents each element in the set. In this case, each element is an object 2. Index represents the subscript 3 of each element in the collection. MemberList is the array 4 to loop through. Why do we put (item,index) in memberList on every cyclic DOM, The li tag only gets all of the properties of the item object from the li node and all of the children of the element 5.@click=”memberDetail(index)” there’s a click method here, we take index as an argument to the method, what’s the purpose, This index represents the subscript of each cycled DOM. By clicking, we can get the corresponding user ID, so to speak, any value of each user, and then we can operate in Methods. We can save it in sessonStorage to transfer to the next user sentiment page to obtain all user details. We can open Google Chrome, and when we click with the mouse, we can find changes in sessionStorage
This process is a must for any medium-sized project
2.template v-for
Like the V-if template, you can also render multiple element blocks with the
tag with v-for, loiterating block areas
Application scenario: When we loop rendering, if we have multiple improper relationships, the general situation must be in the outermost div element, this I think is not very clear, we use template instead of rendering, not only can save a lot of DOM nodes, but also can solve the improper situation
<template> <div> <template v-for="item in list"> <p>{{item.content}}</p> <img :src="item.img" alt=""> <p class="divider"></p> </template> </div> </template> <script> export default { data () { return { list : [ {content : 'ziksang' img: 'https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=1301074775, & FM = 80 & 1382810875 w = 179 & h = 119 & img. JPEG'}, {content : 'ziksang2' img: 'https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=1312092207, & FM = 80 & 1376369244 w = 179 & h = 119 & img. JPEG'}}}] } </script> <style> body,html{ width:100%; height:100% } .divider{ width:100%; height:1px; background:black; } </style>Copy the code
If you don’t want to create multiple nodes and don’t want p elements to be the root node, you can use template to render. In The Chorme developer tool, it can be verified that the outermost template disappears automatically without creating extra nodes.
3. V -for Object rendering
You can also use V-for to iterate through an object’s properties.
Application scenarios: like the first example in details page, if we want to show a user details, if the backend is sorted for you, how to correct and convenient display, with the fastest and most convenient method that is v – for iterative object, usually show a user details, background must return a user object to you
<template> <table> <template> <tr> <td v-for="(value,key,index) in memberDetail">{{key}}</td> </tr> <tr> <td v-for="(value,key,index) in memberDetail">{{value}}</td> </tr> </template> </table> </template> <script> export default Created () {this.memberDetail = {name: 'ziksang', age: 20, address: "XXX city, XXX province ", tel: "15921898427"}}, data () {return {memberDetail: {} } } } </script> <style> body,html{ width:100%; height:100% } .divider{ width:100%; height:1px; background:black; } </style>Copy the code
Key represents the attribute, index represents the subscript index of each DOM node. There is a one-to-one correspondence between the two. Through the first example, I believe this example is very simple
4. V-for integer iteration
I’ll just look at the demo, I’ve barely used it
<div>
<span v-for="n in 10">{{ n }}</span>
</div>
Copy the code
4. V-for and components
In custom components, you can use V-for just like any normal element.
Application scenarios: for the nuggets, for instance, each user in the list of articles, each user’s articles can be made into a unified component, by the parent component for data transfer, circulation out of all the articles, it formed a list of articles, but also in the popular, new, or column reuse, only needs through data transmission, is a pretty good model
Create a myArticle file in the Components folder
<template> <div> <p>{{artList.name}}</p> <p>{{artList.startTime}}</p> <p>{{artList.content}}</p> <p>{{artList.good}}</p> </div> </template> <script> export default { props : ['artList'] } </script>Copy the code
Render the component using the props option to receive data from the parent component
App. Vue file
<template> <div> <my-article v-for='item in artList' :art-list='item'></my-article> </div> </template> <script> import myArticle from "./components/myArticle.vue" export default { components : {myArticle}, created () {this.artList = [{name: 'ziksang1', startTime: {name :' ziksang2', startTime :' 2', content:' BBBBBBBBB ',good: 1}, {name :' ziksang2', startTime :' BBBBBBBBB ',good: 2}, {name: 'ziksang3, startTime:' 3 hours ago, content: "CCCCCCCCC", good: 3}, {name: 'ziksang4, startTime: '4 hours ago ', Content :' DDDDDDDDD ',good: 4}]}, data () {return {artList: []}}}Copy the code
This needs to be analyzed line by line 1. First we introduce component 2.v-for to loop component 3. Pass the data from each article to the myArticle component with :art-list=’item’. If we do pull-down load and pull-up refresh, we simply re-assign the data to the child component, and we can reuse the component from page to page to reduce the development effort
4. Array update detection
1. Array variation
In simple terms, we can change the data option directly using the array. prototype prototype method, which triggers the view update. 1.push() 2.pop() 3.shift() 4.unshift() 5.splice() 6.sort() 7.reverse()
Application scenario, let’s say we are desperate background controller, we are bored to see the article is not happy, we operate on the article, this is just my nonsense to play with the scene, is to use the scene to simulate the use of the scene
App. Vue file
<template> <div> <my-article v-for='item in artList' :art-list='item'></my-article> <button @click='push'> < button@click ='pop'> </button> < button@click ='unshift'> Add data to the header </button> <button @click='shift'> </button> <button @click='reverse'> </button> </div> </template> <script> import myArticle from "./components/myArticle.vue" export default { components : {myArticle}, created () {this.artList = [{name: 'ziksang1', startTime: {name :' ziksang2', startTime :' 2', content:' BBBBBBBBB ',good: 1}, {name :' ziksang2', startTime :' BBBBBBBBB ',good: 2}, {name: 'ziksang3, startTime:' 3 hours ago, content: "CCCCCCCCC", good: 3}, {name: 'ziksang4, startTime: }, data () {return {artList: []}}, methods: {this.artlist.push () {this.artlist.push ({name :' ziksang5', startTime :' 5 hours ago ', Content :' eeeeeeeeeeee ', good: 5}) }, pop () { this.artList.pop() }, shift () { this.artList.shift() }, unshift () { this.artList.unshift({ name : 'ziksang3', age : 40 }) }, reverse () { this.artList.reverse() }, clear () { this.artList = [] } } } </script>Copy the code
We found that when we click these buttons, the myArticle view changes at the same time. This is the effect we need
2. Array non-mutation
In the prototype Array, no mutation methods are used to change the view of the artList Array. The rest of the methods return a value after the operation, and all the other methods return a new Array. 1.filter(), 2.concat(), 3.slice(), 4.map()
<template> <div> <ul> <li v-for = " (item,index) in list" v-text='`${item} - ${index} `'></li> </ul> <button @click="filter"> </button> <button @click="concat"> </button> <button @click="map"> </button> <button @click="slice"> </button> </div> </template> <script> export default {data () {return {list: [ 1, 2, 3, 4], list2 : [ 7, 8, 9, 0 ] } }, methods : {this.list = this.list.filter() {this.list = this.list.filter((item)=>{return item % 2})}, concat () {// Both methods can be used //1. The first is a deconstruction of es6 operator / / 2. The second is the traditional array merge enclosing list = [... this list,... this. List2]. / / this list = enclosing a list. The concat (enclosing list2)}, map () { this.list = this.list.map(item =>{ return `${item} map` }) }, slice () { this.list = this.list.slice(2) } } } </script>Copy the code
The final goal is to change the view update method, which is easy to do, as long as the resulting return value is reassigned to the Array in the data option. The API documentation is very advanced, but the basic principle is array. prototye method guide, I believe you must be clear. Above I also have the code for… Deconstructing the new feature gives you an example
4. Pay attention to the instructions
Official note: Due to JavaScript limitations, Vue cannot detect the following changes to an array: when you set an item directly using an index, e.g. Vm. items[indexOfItem] = newValue When you change the length of an array, e.g. vm.items.length = newLength
in
<template> <div> <ul> <li v-for = " (item,index) in list" v-text='`${item} - ${index} `'></li> </ul> <button </button @click="change4" </button> </div> </template> <script> import Vue from 'vue' export default { data () { return { list : [ 1, 2, 3, 4], list2 : [ 7, 8, 9, 0 ] } }, methods : ChangeList () {this.list[2] = 3}; changeList2 () {this.length = 1}; // First we can change it by using vue. Set. Vue. Set (example1.items, indexOfItem, NewValue) change3 () {Vue. Set (this.list,1,0)}, // use array.prototype.splice to change the length or content of Array. Change4 () {this.list.splice(1,1,5)}}} </script>Copy the code
I’m just going to comment it out in the code because of the manipulation, just to give you a little bit more clarity, how do I change the length of an array, how do I change an element of the index
5. Display the filtering or sorting effect
For my understanding, I define it as a copy filter, which does not change the original array of data options while changing the new array, and at the same time does not create redundant data values. Then we need to use a calculation attribute application scenario described in Foundation 3: I’ve done a little demo here where when you randomly change the values in the original array, the copy creates a copy of the original array that changes depending on the filter and has two views: 1. In the first view, we click the button to change the random number from 1 to 10 2. In the second view, we filter out the random number as it changes to determine whether it is even or even
<template> <div> <ul> <li v-for = " (item,index) in list" v-text='`${item} - ${index} `'></li> </ul> <ul> <li v-for = " (item, index) in the filter "v - text = '${item} - ${index} ` `' > < / li > < / ul > < button @ click =" randomList "> reset random array values < / button > < / div > </template> <script> export default { data () { return { list : [1, 2, 3, 4]}}, // The detection computates the different filter results as the original array is changed with random numbers. The filter result is that the original array is composed of even values into a new array //1. We can also use methods, but can't always monitor computed: {filter() {return this.list.filter((item)=>{return item % 2})}}, methods: {this.list = this.list. Map (item => {return item+ math.round (math.random ()*9+1)}) {this.list = this.list. } } } </script>Copy the code
As we click the button, both views are updated at the same time, essentially filtering out a new array in the Data option, and this new array does not affect the array in the Data option. This is called duplicate filtering, and you can make many different demo examples by your own imagination
If you paste this code into vue-CLI to understand it, and then type two demos by yourself, I think your project development speed will definitely double. Finally, don’t expect it to be nice. Again, my update speed, Depends on your approval of me. Thank you
Nuggets in the history of the most detailed VUE2.0 full set of demo (foundation 3) ==> calculation of properties
Dregs front-end development engineer, love to study, love to share and explain teaching, Shanghai to my intent front-end development company team directly pulled me away! Cost-effective! B: Kidding! Don’t tease B don’t pay ~ wechat zzx1994428 QQ494755899
If you support me to continue to create and feel fruitful, please send me a tip
If reproduced please mark from @ mixed yuan thunderbolt hand Ziksang