Skip to main content
Category:

If you – for whatever reason – want to only output something one time, then you can use the v-once directive. This directive ensures that an element is only rendered once, and when Vue.js re-renders the page, the element and all of its children will be considered as static content and thereby skipped.

An example usage of the v-once directive is for optimizing the performance when updating data on the page.

In the example that I have prepared for you, I simply output the title of a movie using string interpolation, and I also have a button which simply updates the movie title to a different movie. If I click the button, you will see that the text changes as you would expect.

Now I will simply add the v-once directive to the h1 element like this:

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

 

The v-once directive does not expect an expression, so this is actually all we need to do. So if I click the button now, we will see that the text is no longer updated, even though a new value is in fact assigned to the data property.

This is because the h1 element will not be re-rendered after it has been rendered initially, so when Vue.js processes data changes, it will simply ignore the element.

If the element had any children, these would also be ignored, even if they contained any string interpolation for example.

 

<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <h1 v-once>{{ movieTitle }}</h1>
  
  <button v-on:click="movieTitle = 'The Matrix Reloaded'">Change Movie Title</button>
</div>

new Vue({
    el: '#app',
  data: {
        movieTitle: 'The Matrix'
  }
});

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook