Vue.js Study conditions V-if and list loop v-for detailed

Source: Internet
Author: User

This article will continue to share with you the basic knowledge of vue.js, mainly introduces Vue.jsthe conditionsv-ifand List Loopsv-forRelated use, come together to see it, hope can help everybody better study vue.js. V-if,V-else,V-show, you can also useTemplate<div v-if= "OK" >ok</div><div v-else>no</div><div v-show= "OK" >ok</div>< Template v-if= "OK" ><strong>Testtemplate</strong></template><template V-else><strong>no template</strong></template> DemoList LoopsV-for Loop array <ul><li v-for= "Todo in Todos" >{{todo.text}}</li></ul>A multilevel list, the second parameter provides the index of the current item,TemplateTemplates<div v-for= "items in List" ><template v-for= "(item, index) in items" >{{index}}-{{item.message}}<br/> </template></div> Object iteration: A parameter as the value <div v-for= "value in Object" >{{value}}</div> the second argument as the key name <div V-for= "(Value,key) in Object" >{{key}}-{{value}}</div> the third parameter as the index of the current item <div v-for= "(Value,key,index) in Object ">{{index}}-{{key}}: {{value}}</div>Componentsand theV-forloop array data into the component, using theProps, the value and the current index can be assigned to the component. <my-componentv-for= "(item, index) in items" v-bind:item= "item" v-bind:index= "index" ></my-component>or the following adds some semantic tags that have aIs= "Component Name"<liis= "Todo-item" v-for= "(Todo, index) in Todos" v-bind:item= "Todo" v-on:remove= "Todos.splice (Index, 1)" ></ Li> Below is a complete example: <div id= "Todo-list-example" >        <input        V-model= "Newtodotext"         v-on:keyup.enter= "Addnewtodo"         placeholder= "Add a Todo"         >        <ul>          &NBSP ;     <li                is= "Todo-item"         &NBS P       v-for= "(Todo, index) in Todos"                 v-bind:item= "to Do "                v-on:remove=" Todos.splice (Index, 1) "                ></li>        </ul></div>vue.component (' Todo-item ', {        Template:'         <li>        {{Item}}            &NB Sp   <button v-on:click= "$emit (\ ' remove\ ')" >X</button>        </li>        ',        props: [' Item ']}) New Vue ({        el: ' #todo-list-e Xample ',        data: {              Newtodotext: ',                Todos: [                ' Do the D Ishes ',                ' take-out ' the trash ',          &NB Sp     ' Mow the lawn '        },        methods: {      &NBSP ;         addnewtodo:function () {                        This.toDos.push (this.newtodotext)                         This.newtodo Text = "               }       }})UsePropsassigns the index entry and value of the array loop to the current componentfind a detail that is the component templateTemplateBranch to add a\,There is also a semicolon inside the double quotation mark .\.using the current execution function,$emit (\ ' remove\ ');Removeis bound to theDOMfunctions in the. in order to giveVuea hint so that it can track the identities of each node, thus reusing and reordering existing elements, you need to provide each item with a uniqueKeyproperty. Ideal forKeyvalue is unique for each itemID. This special property is equivalent toVue 1.xof thetrack-by, but it works like a property, so you need to useV-bindto bind the dynamic value (use shorthand here):<div v-for= "Item in Items": key= "item.id" ><!--content -</div>It is recommended to use asV-forto provideKey, unless the iterationDOMthe content is simple enough, or you deliberately rely on the default behavior to get a performance boost. because it isVueA common mechanism for identifying nodes,Keynot particularly withv-forAssociation,KeyThere are other uses as well, and we'll see other uses in the guide later. Array Update detection Vuecontains a set of variation methods for observing arrays, so they will also trigger view updates. These methods are as follows:Push () Pop () Shift () Unshift () splice () sort () reverse ()you open the console and use the previous exampleItemsArray Call mutation method:Example1.items.push ({message: ' Baz '}). Reshape an arrayMutation Method(Mutation method), as the name implies, changes the original array that is called by these methods. In contrast, there are non-mutated(Non-mutating method)methods, such as:filter (), concat (), Slice (). These do not change the original array, but always return a new array. When using a non-mutating method, you can replace the old array with a new array:Example1.items = Example1.items.filter (function (item) {return Item.message.match (/foo/)})you may think that this will leadVueDiscard ExistingDOMand re-render the entire list. Fortunately, that's not the case. VueSome intelligent heuristic methods are implemented to maximizeDOMelement Reuse, it is very efficient to replace the original array with an array containing the same elements. PrecautionsbecauseJavascriptthe restrictions,Vuecannot detect an array of the following changes:when you set the index of an item directly, for example:Vm.items[indexofitem] = newvalueWhen you modify the length of an array, for example:Vm.items.length = Newlengthin order to avoid the first case, the following two ways will be achieved likeVm.items[indexofitem] = newvalueAnd also triggers a status update:Vue.setVue.set (Example1.items, Indexofitem, NewValue)//Array.prototype.splice ' Example1.items.splice ( Indexofitem, 1, NewValue)to avoid the second case, useSplice:Example1.items.splice (Newlength)Display Filter/Sort ResultsSometimes we want to display a filtered or sorted copy of an array without actually altering or resetting the original data. In this case, you can create a computed property that returns a filtered or sorted array. For example: <li v-for= "n in evennumbers" >{{n}}</li>data: {numbers: [1, 2, 3, 4, 5]},computed: {evennumbers:functio N () {return this.numbers.filter (function (number) {return number% 2 = = = 0})}}or, you can also use the property in the calculation is not feasibleMethodMethod(For example, in nestedv-forin the Loop):<li v-for= "N in even (numbers)" >{{n}}</li>data: {numbers: [1, 2, 3, 4, 5]},methods: {even:function (number s) {return Numbers.filter (number) {return number% 2 = = 0})}} Article source: Front-end Development blog

Vue.js Study conditions V-if and list loop v-for detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.