VUE

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.

Disqus Comments Loading...
Share
Published by
Karthik Chintala

Recent Posts

2 Good Tools To Test gRPC Server Applications

In this post, we’ll see how to test gRPC Server applications using different clients. And… Read More

2 years ago

Exploring gRPC project in ASP.NET Core

In this post, we'll create a new gRPC project in ASP.NET Core and see what's… Read More

2 years ago

Run dotnet core projects without opening visual studio

In this blog post, we’ll see how to run dotnet core projects without opening visual… Read More

2 years ago

Programmatically evaluating policies in ASP.NET Core

Programmatically evaluating policies is useful when we want to provide access or hide some data… Read More

2 years ago

Multiple authorization handlers for the same requirement in ASP.NET Core

We saw how we could set up policy-based authorization in our previous article. In this… Read More

2 years ago

Policy-Based Authorization in ASP.NET Core

What is policy-based authorization and how to set up policy-based authorization with handlers and policies… Read More

2 years ago

This website uses cookies.