Private variables in VueJS

private variables in vuejs

Most of the times when we want to create a variable to be used in a vue file, we will create a property in the data() function. But, if we don’t want the property to be reactive, then we’d have to create a private variable or a variable that is not reactive.

There’s no official documentation about creating private variables in Vue files. (I couldn’t find it)

Private variables

Creating variables in the created() hook is the way to have private variables.

When the created hook is called, vue has already finished the observation phase. So, these variables created after the observation phase are not reactive.

created: function () {
    this.myStuff = '';
}

Test for reactivity in the private variables

Let’s add a private variable in the created hook and use the same variable in the vue template. To modify the private variable let’s add a button as well.

The test is to verify if the template updates when we change the value of the variable in the button click.

<h3>data: {{ myStuff }}</h3>
<button @click="addStuff">say Hello</button>
<script>
export default {
  name: "HelloWorld",
  created: function() {
    this.myStuff = "";
  },
  methods: {
    addStuff: function() {
      this.myStuff = "Hello";
    }
  }
};
</script>

Test passed!

Clicking the say hello button does nothing. So, the private variable is not reactive.

Here’s the demo of it in code sandbox.