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)
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 = ''; }
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.
Karthik is a passionate Full Stack developer working primarily on .NET Core, microservices, distributed systems, VUE and JavaScript. He also loves NBA basketball so you might find some NBA examples in his posts and he owns this blog.
In this post, we’ll see how to test gRPC Server applications using different clients. And… Read More
In this post, we'll create a new gRPC project in ASP.NET Core and see what's… Read More
In this blog post, we’ll see how to run dotnet core projects without opening visual… Read More
Programmatically evaluating policies is useful when we want to provide access or hide some data… Read More
We saw how we could set up policy-based authorization in our previous article. In this… Read More
What is policy-based authorization and how to set up policy-based authorization with handlers and policies… Read More
This website uses cookies.