V-once in Vue.js

V-once is a Vue.js directive that will render an element or component only once. On subsequent re-renders, the HTML element holding the v-once directive will not update. To demonstrate how this works take a look at the simple “Hello World” setup below.

<div id="app">
 <h1>{{ greeting }}</h1>
 <p>{{ sayGreeting() }}</p>

 new Vue({
   el: "#app",
   data: {
     greeting: "Hello World!",
   methods: {
     sayGreeting: function(){
       this.greeting = "Greetings";
       return this.greeting

The example above begins with a simple “Hello World!” that’s stored in data with the variable greeting. A method below called sayGreeting calls an update on greeting with this.greeting and displays the message “Greetings.” If you render this view as it’s written, both h1 and p tags will display the word “Greetings.”

If you want both h1 and p tags to display “Greetings” then this code is fine. But it does bring up the question, how do you display what’s stored in the greeting data variable? The answer is a v-once directive.

<h1 v-once>{{ greeting }}</h1>

By inserting v-once in the h1 tag “Hello World!” will now up be displayed there, while “Greetings” is displayed in the p tags.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s