Pekehata
Pekehata

Reputation: 29

Vue: Updating a data property triggers re-evaluation of entire data?

I've been working on Vue project for almost a year, and I've just observed unexpected behavior below for the first time today...

Here is a link to code sandbox: https://codesandbox.io/s/2bnem?file=/src/App.vue

And a code snippet from above link:

<template>
<div>
  <div>{{a}}</div>
  <div>{{translator(b)}}</div>
  <input v-model="a" />
</div>
</template>

<script>
export default {
  data() {
    return {
      a: 'a',
      b: 'b',
    }
  },
  computed: {
    translator: function() {
      return function(value) {
        console.log(`translated...: ${value}`)
        return value
      }
    }
  }
}
</script>

Now every time I hit the key on input, the translator is triggered. Is this a correct behavior? If so, what is the cause of this problem or a background reasoning of this behavior?

Note that my vue version is 2.6.14(latest).

Upvotes: 0

Views: 161

Answers (1)

Phil
Phil

Reputation: 165065

Your original issue is that you were attempting to use a method to render parts of your template. Methods used like this will execute for every update cycle, regardless of what changed.

The better solution is to use a computed property. Here's a somewhat dynamic example that wraps each of your data properties with a computed translator_x property

<template>
  <div>
    <div>{{ a }}</div>
    <div>{{ translator_b }}</div>
    <input v-model="a" />
  </div>
</template>

<script>
const defaultData = {
  a: "a",
  b: "b"
}
export default {
  data: () => ({ ...defaultData }),
  computed: Object.fromEntries(Object.keys(defaultData).map(k => [
    `translator_${k}`,
    vm => {
      console.log("translated...", k)
      return vm[k]
    }
  ]))
};
</script>

Each translator_x property will only be evaluated if the underlying data property is changed.

Edit dreamy-sky-bgj5h

Upvotes: 1

Related Questions