Vue.js efficient front-end development [Vue list rendering]

All chapters > > > >

Article catalogue

1, v-for instruction

1. Use of v-for instruction

  • The v-for instruction repeats rendered elements based on an array.
  • The v-for instruction is usually used to display list and table data.
  • The v-for instruction needs to use a special syntax in the form of "item in items", where items is the source data array and item is the alias of the array element being iterated. In the v-for block, developers can access the properties of the parent scope.
  • v-for also supports an optional second parameter, the index of the current item.
  • In order to give Vue a hint so that it can track the data of each row and reuse and reorder existing elements, the v-for instruction needs to provide a unique key attribute for each item.

Example: using v-for to display a list of employee information

<!-- HTML code: -->
<div id="app" style="margin:20px auto;width:600px">
  <ul>
    <li v-for="(item,index) in items" :key="index">
      <a href="">{{ index }}.{{ item }}</a>
    </li>
  </ul>
</div>


// JavaScript code:
var vm = new Vue({
  el: "#app",
  data: {
    items:["Department management","Employee management","Job management"]
  }
})


Example: using the v-for command to display individual employee information

<!-- HTML code: -->
<div id="app" style="margin:20px auto;width:600px">
  <div v-for="(value,name,index) in emp">
    {{ index }}.{{ name }} : {{ value }}
  </div>
</div>


// JavaScript code:
var vm = new Vue({
  el: "#app",
  data: {
    emp:{
      user:"Zhao Wu",
      age:20,
      job:"project manager"
    }
  }
});

The v-for instruction can also traverse the properties of an object. The v-for instruction can provide the second parameter as the property name (that is, the key name), and can also use the third parameter as the index.

When Vue is updating the list of elements rendered using v-for, it defaults to the update in place policy. If the order of data items is changed, Vue will not move DOM elements to match the order of data items, but update each element in place and ensure that they are rendered correctly at each index position. This default mode is efficient, but it is only applicable to list rendering output that does not depend on subcomponent state or 'temporary DOM state' (e.g. form input value).

explain:

It is recommended to use it as much as possible v-for When provided`key attribute`,Unless traversing the output DOM The content is very simple, or it deliberately relies on the default behavior to improve performance.

be careful:

Do not use non basic type values such as objects or arrays as v-for of key. Please use a value of string or numeric type.

2. Practical exercises (to be updated)

2, Calculation properties

1. Calculation attribute creation and use

  • The expressions in the template are very convenient, but they are designed for simple operations. Putting too much logic in the template will make the template too heavy and difficult to maintain. for example

    {{ message.split('').reverse().join('') }}
  • In this place, templates are no longer simple declarative logic. You have to look for a while to realize that here is the flipped string of the variable message you want to display. When you want to reference the flipped string here multiple times in the template, it will be more difficult to deal with.

  • Therefore, for any complex logic, computational properties should be used.

  • In the calculation attribute, various complex logic can be completed, including operation, function call, etc., and the final result will be returned.

  • The calculation attribute can also depend on the data of multiple Vue instances. As long as any of the data changes, the calculation attribute will be re executed and the view will be updated.

  • After all the properties of vuutee are written in the final calculation result of vuuted.

Example: flip English sentences alphabetically using calculated attributes

<!-- HTML code: -->
<div id="app" style="margin:20px auto;width:600px">
  <p>Original string: "{{ message }}"</p>
  <p>After string conversion: "{{ reversedMessage }}"</p>
</div>


// JavaScript code:
var vm = new Vue({
  el: "#app",
  data: {
    message:"Failure is the mother of success."
  },
  computed: {
    reversedMessage:function(){
      return this.message.split("").reverse().join("");
    }
  }
})

The functions of the example can also be realized by using the Vue instance option methods method. The difference between the methods method and the calculation attribute is that the calculation attribute supports caching, so it is more efficient to calculate the attribute when traversing a large array or doing a lot of calculations.

Example: use the calculation attribute to realize the function of searching the string array according to the keyword

<!-- HTML code: -->
<div id="app" style="margin:20px auto;width:600px">
  <span>String keyword:</span>
  <input type="text" placeholder="Please enter keyword..."  v-model="wordKey"/>
  <ul>
    <li v-for="item in findItems" :key="item">
      {{ item }}
    </li>
  </ul>
</div>


// JavaScript code:
...
el: "#app",
data: {
  items:[...],
  wordKey:""
},
computed: {
findItems:function(){
  var _this=this;
  //Filter the data in the array according to the conditions
  return _this.items.filter(function(val){
    return val.indexOf(_this.wordKey)!=-1;
  })
}

2. Practical exercises (to be updated)

3, Listening properties

1. Create and use listening properties

  • Vue provides a more general way to observe and respond to data changes on Vue instances: listening properties. When some data needs to change with other data changes, you can use the listening attribute watch.
  • Watch is an object, in which the attribute of watch object is the target that needs to be listened to, generally a data item in data, and the attribute value of watch object is a function that needs to be executed when the listened data item changes. This function has two formal parameters, the first is the current value and the second is the updated value.

Example: use watch listening to add the commodity information input box, and display different prompt effects according to the change of value

<!-- HTML code: -->
<div id="app" style="margin:20px auto;width:600px">
  <div class="prod">
    <h1>Commodity information</h1>
    <p>
      <p><label for="title">Item title:</label>
        <input type="text" v-model="title" />
        <span :class="{ warn:!titleValid}">Item title cannot be blank!</span></p>
      <p><label for="price">Unit price of goods:</label>
        ...</p>
      <p><label for="amount">Quantity of goods:</label>
        ...</p>
      <p>{{ title }}>Goods purchased{{ amount }}book,total&yen;{{ total }}element</p></p>
  </div>
</div>


// JavaScript code:
var vm = new Vue({
  el: "#app",
  data: {
    title:"JavaScript Authoritative guide",
    price:"40",
    amount:"10",
    total:"0",
    titleValid:true,
    priceValid:true,
    amountValid:true
  },
  watch: {
    title: function(newVal, oldVal){      ...    },
    price: function(newVal, oldVal){      ...    },
    amount: function(newVal, oldVal){     ...    },                
  },
})

The watch option parameter contains functions that listen for changes in the values of the item title, price, and amount

A feature of watch is that it will not be executed when it is initially bound. It will not be executed until the unit price and quantity of goods change

If you want to execute at the beginning of the initial binding, you need to use the handler method and immediate attribute in the watch:
handler() method: its value is a callback function. That is, the function that should be executed when monitoring the change.
immediate attribute: its value is true or false; Confirm whether to execute the handler function with the current initial value.

Example: modify the following code of price() in the watch of the previous example

// JavaScript code:
price:{ 
// The previously written function of watch is actually written as handler by default
  handler:function(newVal, oldVal){
     ...
  },
  // If the representative declares price in wacth, he will immediately execute the handler method inside
  immediate:true
}

  • The default value of the object is whether to listen for the data. If the object needs to listen for a change, the default value of the object is whether to listen for the data. If the object needs to listen for a change, the default value of the object is whether to listen for the data.
  • When the deep attribute is true, you can listen for changes in object attributes.

2. Practical exercises (to be updated)

4, Comprehensive case

1. Commodity information management

The management function of commodity information is realized by combining the basic knowledge of Vue, including the following functions:

  • Add product information.
  • Displays a list of all product information.
  • Query the commodity information list according to the commodity title.
  • Delete product information.

This section only uses JavaScript, CSS and HTML to realize the front-end part, and does not involve server-side functions and database parts.

Realize the function of adding commodity information

  • Create view
  • Define model
  • Define add method
// JavaScript code:
var vm = new Vue({
  el: "#app",
  data: {
    ...Omit code...
  },
  methods: {
    createProd: function () {
      this.products.push(this.newProduct);
      // After adding the newProduct object, reset the newProduct object
      this.newProduct = {
        name: "",
        price: 0,
        category: "mobile phone/Digital",
      }
    }
  }
});

Realize the display of all commodity information list

<!-- HTML code: -->
<table>
  <thead>
    <tr>
      <th>name</th>
      <th>Price</th>
      <th>category</th>
      <th>delete</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(prod,index) in findProdList">
      <td>{{ prod.name }}</td>
      <td>{{ prod.price | priceFormat }}</td>
      <td>{{ prod.category }}</td>
      <td class=""text-center""><button @click="deleteProd(index)">delete</button></td>
    </tr>
  </tbody>
</table>


// JavaScript code:
var vm = new Vue({
  el: "#app",
  data: {
    ...Omit code...
  },  
  // In order to display the price correctly, the filter is used for format processing
  methods: {
    ...Omit code...
  },
  filters: {
    priceFormat: function (val) { // Create Price format filter
      return "¥" + parseInt(val).toFixed(2) + "element";
    }
  }
});

Query the commodity information list according to the commodity title

<!-- HTML code: -->
<div id="app">
...Omit code...
<div class="form-group">
<label>Query keyword:</label>
<input type="text" v-model="key" placeholder="Please enter query keyword...." />
</div>
...Omit code...
</div>


// JavaScript code:
computed: {
  findProdList:function(){
    var _this=this;
    return _this.products.filter(function(prod){
      return prod.name.indexOf(_this.key)!=-1;
    });
  }
}

Realize the function of deleting commodity information

// JavaScript code:
var vm = new Vue({
  el: "#app",
  data: {...Omit code...},
  filters: {...Omit code...},
  methods: {...Omit code...
  //Add deleteProd() method
    deleteProd: function (index) {
      if (confirm("Delete current product information?")) {
        // Delete an array element
        this.products.splice(index, 1);
      }
    }
  },
  computed: {...Omit code...}
});

2. Practical exercises (to be updated)

summary

  • In general projects, it is often necessary to display information in tables or lists. The v-for instruction is provided in Vue to support the circular list function.
  • Avoid adding too much business logic into the template to calculate attributes, and ensure the clarity and maintainability of the template structure
  • When some data needs to change with other data changes, you can use the listening attribute watch.

Keywords: Javascript Front-end Vue.js html

Added by rlindauer on Wed, 09 Mar 2022 03:17:49 +0200