Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

In the process of development, defining variables is a very frequent and basic thing. How to reasonably define variables according to the use scenarios and scope of variables is a very small thing that is easy to make mistakes

Vue2 has been widely used for many years. Most developers like to define many variables in the data option during the development process, which is very bad for the code readability, maintainability and performance. To use variables well, you need to combine Vue and JS features

In Vue, variables can be divided into two types, depending on whether bidirectional data binding is required:

One is to be hijacked by Vue’s data and respond to changes in data in real time to the View

As long as data can only change MSG, the MSG bound to the template responds in real time

<template>
  <div>{{msg}}</div>
</template>

<script>
export default {
  data() {
    msg: "" 
  }
};
</script>
Copy the code

And one that doesn’t need to be hijacked by Vue data:

Valid only in script, not template, and does not require data hijacking

Name only works in the concatName function, so define it as a local variable

Age is used in both getAge and concatName and is not appropriate as a local variable, so it can be scoped to make it easier to use in multiple places

<script>
const age = 'bar'
export default {
  methods: {
    getAge() {
      return age
    },
    concatName() {
      let name = 'nordon'
      reutrn `name:${name}, age: ${age} `
    }
  },
};
</script>
Copy the code

It is only used as render data in the template and is not modified in subsequent operations after customization. Hijacking such data using Vue wastes some performance

<template>
  <div v-for="item in arr">{{item.name}}</div>
</template>

<script>
const arr = Object.freeze([{
  name: 'nordon',
  age: 18
}])
export default {
  data() {
    return {
      arr
    }
  }
};
</script>
Copy the code

Freeze is used to freeze data that does not need data hijacking. When data hijacking is performed recursively in Vue, data hijacking will not be performed, especially for a large number of table classes

Object. Freeze is used to process data, but data hijacking is not performed

function defineReactive (obj, key) {
  // Remove extraneous code only to preserve the judgment criteria
  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return}}Copy the code