Vue computed attribute-computed (interview questions)

Goal: a data, the result calculated by relying on other data

 grammar:

computed: {
    "计算属性名" () {
        return "值"
    }
}

example

<template>
  <div>
    <h4>计算属性</h4>
    <input type="text" v-model.number="a">+
    <input type="text" v-model.number="b">=
    <input type="text" v-model.number="total">
    <div>{
   
   {total()}}</div>
  </div>
</template>

<script>
 export default {
  computed:{
    total(){
      console.log('计算属性执行了');
      return this.a +this.b
    }
  },
  data(){
    return {
      a:6,
      b:8
    }
  },
}
</script>

.Difference between computed properties and methods (interview questions)

  • performance

        Computed properties have a cache, and when dependencies change, the calculated properties will recalculate the results

        Method layouts are cached

  • grammar

       Computed properties belong to property calls without adding ()

        Add () when calling the function

example

<template>
  <div>
    <div>{
   
   {total}}</div>
    <div>{
   
   {total}}</div>
    <div>{
   
   {total}}</div>
    <hr>
    <div>{
   
   {sum()}}</div>
    <div>{
   
   {sum()}}</div>
    <div>{
   
   {sum()}}</div>
  </div>
</template>
<script>
export default {
  computed:{
    total(){
      console.log('计算属性执行了');//只执行一次
      return this.a +this.b
    }
  },
  data(){
    return {
      a:6,
      b:8
    }
  },
  methods: {
    sum(){
      console.log('方法被调用了');
      return this.a +this.b

    }
  }
}
</script>

 print result

Advantage:

  • with cache
  • After the function corresponding to the calculated property is executed, the return value will be cached
  • The dependencies are unchanged, and multiple calls are directly from the buffer area.
  • Dependency value - changes, the function will "automatically" re-execute and cache the new value

Supongo que te gusta

Origin blog.csdn.net/jewels_w/article/details/125565092
Recomendado
Clasificación