Do not put data in data that is not related to rendering

Data in VUE is bidirectional data binding by default. If a large amount of data irrelevant to rendering is directly placed in data, the performance consumed by bidirectional data binding will be wasted. The columns data in the table can be separately extracted from an external JS file as a configuration file, or a constant can be defined in the current. Vue file to define the columns data. Because data is fixed and will not be modified anyway, you should wrap it with Object.freeze to both improve performance and remove fixed data. This is also recommended for some fixed data at the front of drop-down boxes.

const columnList = Object.freeze([
  { title: 'name'.key: 'name'.align: 'center' },
  { title: 'gender'.key: 'gender'.align: 'center'}])Copy the code

Note that object.freeze () can still be used to replace references to variables when the value is frozen. You can also use this syntax to ensure that the data does not change.

Control of the Modal box

A page usually exist a number of different functions of box, if every bullet box set a corresponding variable to control the display, leads to a variable quantity is redundant and naming difficulty, you can use a variable to control all the Modal in the same page display box Such as a page three Modal in the box

// bad
// Each data control corresponds to Modal display and hide
new Vue({
    data() {
        return {
            modal1: false.modal2: false.modal3: false,}}})// good
// Display the corresponding pop-up box when modalType is the corresponding value
new Vue({
    data() {
        return {
            modalType: ' ' // modalType is modal1, modal2, modal3}}})Copy the code

Debounce use

For example, in remote search, data is dynamically obtained through an interface. If the interface requests each user input, bandwidth and performance are wasted

Multiple clicks of a button trigger multiple events. You can determine whether to execute the immediate command based on the scenario

<Select :remote-method="remoteMethod">
    <Option v-for="item in temoteList" :value="item.value" :key="item.id">{{item.label}}</Option>
</Select>
Copy the code
import {debounce} from 'lodash'Methods: {remoteMethod: debounce(function (query) {
        // to do ...
       // This is not a problem
    }, 200),}Copy the code

Route component parameters are transmitted

Using $route in a component makes it highly coupled to its corresponding route, limiting its flexibility by limiting its use to certain urls.

Decouple components and routes using props:

Replace coupling with $route

const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
  routes: [{path: '/user/:id'.component: User }
  ]
})
Copy the code

Decoupled by props

This allows you to use the component anywhere, making it easier to reuse and test.

const User = {
  props: ['id'].template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
  routes: [{path: '/user/:id'.component: User, props: true },

    // For routes that contain named views, you must add the 'props' option for each named view:
    {
      path: '/user/:id'.components: { default: User, sidebar: Sidebar },
      props: { default: true.sidebar: false}}}])Copy the code

dataData hierarchy

Data data with hierarchical structure, do not too flat or nested hierarchy too deep, if excessive flat namespace conflicts can lead to data, parameters and process, if it is a nested hierarchy too deep will lead to the vue data hijacking recursion level too deep, if nested hierarchy of ecstasy that, careful recursive stack problem. Moreover, too deep level will lead to inconvenient data operation and processing, and the acquisition of data for fault tolerance processing is also cumbersome. Generally, it is best to keep 2-3 levels. If there is only one layer of data, it is too flat

{
    name: ' '.age: ' '.gender: ' '
}
Copy the code

The processing is not convenient

// passed as an interface parameter
ajax({
 this.name, this.age, this.gender
})

// Interface to obtain data, batch processing
ajax().then(res= > {
 const {name, age, gender} = res.data
    this.name = name
    this.age = age
    this.gender = gender
})
Copy the code

Proper hierarchy not only increases the maintainability and readability of code, but also the ease of operation and processing

{
    person: { // Personal information
        name: ' '.age: ' '.gender: ' '}}Copy the code

You can operate on Person

// passed as an interface parameter
ajax(this.person)

// Interface to obtain data, batch processing
ajax().then(res= > {
 const {name, age, gender} = res.data
    this.$set(this.'person', {name, age, gender})
})
Copy the code

Functions in methods have a single responsibility

Create () {this.init(); create () {this.init(); Init () {this.getlist1 () this.getlist2 ()}, getList1() {// to do… }, getList2() { // to do … }}

v-bind

In the daily development process, extracting and encapsulating components is a very routine operation. However, when a component needs too many parameters, it will lead to the transfer of a bunch of prop, which is not only tedious to write, but also not beneficial to the maintenance and reading of the code. For example, test-demo requires a bunch of props to pass and use

<template>
  <test-demo 
    :data1="data1"
    :data2="data2"
    :data3="data3"
    .Suppose there's a bunch of />
</template>
Copy the code

Test-demo requires receiving processing

{
	props: ['data1'.'data2'.'data3'. ] }// or
props: {
  modalVisible: {
    // Control display modal
    type: Boolean.default: false
  },
  data1: {
    type: String.default: '1'
  },
  data2: {
    type: String.default: '2'
  },
  data3: {
    type: String.default: '3'}}Copy the code
  • advice

Gather the data required by the sub-components into an object, and pass the object using the V-bind pass, just like normal props

<template>
	<test-demo 
    v-bind="obj"
  />
</template>
Copy the code
export default {
    data () {
        return {
            obj: { // Collect the data that needs to be passed to the child components
                data1: '1'.data2: '2'.data3: '3'
                 }
            }
        }
    }
</script>
Copy the code

Preferred to usev-if

Both v-if and V-show are theoretically used to show and hide elements, one directly on the DOM and the other via CSS display. V-show is preferred only when the DOM is frequently shown and hidden

v-forandv-ifDon’t use it together

V-for has a higher priority than V-if, so when two instructions appear in a DOM, the current list rendered by V-FOR needs a V-IF judgment each time. The corresponding list will also change, which seems very unreasonable. So when you need to do a synchronization command. Use calculated attributes whenever possible, and filter out unwanted values for V-for first. He looks something like this.

// Calculate attributes
computed: {
  filterList: function () {
  return this.showData.filter(function (data) {
    return data.isShow
  })
}
Copy the code
// DOM
  
<ul>
  <li v-for="item in filterList" :key="item.id">
  {{ item.name }}
  </li>
</ul>
Copy the code

v-for keyAvoid the use ofindexAs the logo

In fact, v-for is not recommended to use index index as the key value. This is a very easy point to understand. As you can see from the diagram, when index is used as the identifier, the key after it in the list changes. The current V-Fors all re-render elements with key changes, but they don’t change anything except the Element data they insert, resulting in unnecessary overhead. Instead of using index as an identifier, use unique values in the data, such as id fields.