SoFunction
Updated on 2025-03-03

Detailed explanation of how to define data in Vue

Preface

During the development process, defining variables is a very high-frequency and very basic thing. How to reasonably define variables based on the usage scenario and scope of the variable is a very small and easy to make mistakes.

Vue2 has been popular and used for so many years. Most developers like to define many variables in data options during the development process. This is very unfavorable to the reading, maintenance and performance of the code. If you want to use variables well, you need to combine the characteristics of Vue and JS.

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

One is to be hijacked by Vue's data, and respond to data changes to the view in real time.

As long as data can only change msg, the msg bound in template will respond in real time

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

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

There is another type that does not need to be hijacked by Vue data:

Only effective in script, not used in template, no data hijacking is required

name only takes effect in the concatName function, so it can be defined as a local variable.

Age needs to be used in both the functions getAge and concatName. If it is not suitable to use as a local variable, it can be improved to facilitate use in multiple places.

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

It is just used as rendered data in template, and it will not be modified in subsequent operations after customization. If you use Vue to hijack this data, it will waste some performance.

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

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

Use data that does not require data hijacking for freezing. When recursively traversing data for data hijacking in Vue, data hijacking will not be hijacked. Especially for a large number of table classes, the data performance improvement will be significant.

You can see from the Vue source code why data hijacking will no longer be performed after data processing is used.

function defineReactive (obj, key) {
  // Delete irrelevant code and only the judgment conditions are retained  const property = (obj, key)
  if (property &amp;&amp;  === false) {
    return
  }
}

Summarize

This is the end of this article about how to define data in Vue. For more relevant content on Vue definition data, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!