Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use the lifecycle method beforeMount in vue.js?

Tags:

vue.js

vuejs2

I try to come up with an example when to use each Vue.js lifecycle hook. For beforeMount() I can't come up with any use case. While researching I have als read:

Most likely we’ll never need to use this hook.

Can someone provide an example when I would like to use this lifecycle hook?

like image 702
Simon Thiel Avatar asked Jul 17 '19 13:07

Simon Thiel


People also ask

What is Vue beforeMount?

beforeMount # Called right before the component is to be mounted. When this hook is called, the component has finished setting up its reactive state, but no DOM nodes have been created yet. It is about to execute its DOM render effect for the first time.

What is life cycle in Vue JS?

Lifecycle hooks are pre-defined methods that get executed in a certain order, starting from the initialization of the Vue instance to its destruction. Below is a diagram that indicates the Vue JS lifecycle hooks sequence. There are eight lifecycle hooks in Vue JS: beforeCreate. created.

How do you use the lifecycle hooks at the Vue?

Each Vue component instance goes through a series of initialization steps when it's created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes.

When to use mounted vs created?

Conclusion: mounted () : it will executed before creating the component. created () : it will executed after creating the component for render.


1 Answers

Best use case that I can come up with comes from Directly injecting data to Vue apps with Symfony/Twig. Before the mount happens, you can still see the actual, untransformed Element before it gets replaced by Vue. A particular piece that you can access is the data properties. In the example below, we lose data-fizz if we don't pull stuff out of it before we get to mounted.

const app = new Vue({
  el: "#app",
  data() {
    return {
      foo: "bar"
    };
  },
  template: "<div>{{foo}}</div>",
  beforeMount() {
    console.log(this.$el); // <div id="app" data-fizz="buzz"></div>
    console.log(this.$el.dataset.fizz); // buzz
  },
  mounted() {
    console.log(this.$el); // <div>bar</div>
    console.log(this.$el.dataset.fizz); // undefined
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app" data-fizz="buzz"></div>
like image 76
zero298 Avatar answered Oct 04 '22 21:10

zero298