Search code examples
vue.jsvuejs2vue-componentvuejs3

What's the point of hardcoded class properties in Vue Options API/


Is there a point to defining properties like var_B when using Vue Options API? They are not reachable when defining methods, or inside the template tags. I'm aware I can define variables inside data() for those purposes, but I'm wondering why Vue allows this at all, and if there exists a practical use case

<script>
export default {
  var_B: 10, // WHY DEFINE PROPERTIES HERE AT ALL?
  data() {
    return {
      var_A: 9, 
    };
  },
  methods: {
    double() {
      this.var_A = this.var_A * var_B;
      // causes 9 x undefined  = NaN
    },
  },
};
</script>

<template lang="">
  <div>Variable A: {{ var_A }}</div> <!-- 9 -->
  <div>Variable B: {{ var_B }}</div> <!-- undefined -->
  <button @click="double">Try to Double var_A</button>
</template>

I attempted to use the hardcoded class properties inside the template tags, and inside a method, neither of which worked


Solution

  • data() is a reactive object. It is being watched by Vue for changes and, should any of the values declared in the object returned by data() change, Vue will update all places where it is used (computed, methods, template).

    Declaring custom properties on the base export of a Vue (var_b in your example) is invalid. The application won't error, but nothing you put there is available under this. (or in the template).

    If you want a simple constant read when the component is parsed and don't care about Vue watching it for changes, place it in the root of the <script>:

    const b = 10
    export default {
      data: () => ({
        a: 5
      }),
      computed: {
        c() { return this.a * b }
      }
    }
    

    Whenever you change a, c will automatically become current value of this.a * b.