Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the most recommended syntax for attaching Vue object to an element?

Tags:

When attaching an instance of Vue to a HTML element, I can do in two ways.

  1. By property reference, el:"#rooty"
  2. By method call, $mount("#rooty")

I can't decide between them. Are they precisely equivalent? If one is newer or obsolete'ish, which one is recommended? Is there any other difference and in such case, what would it be?

By property reference.

const app = new Vue({
  store,
  router,
  el: "#rooty",
  ...
});//.$mount("#rooty");

By method call.

const app = new Vue({
  store,
  router,
  //el: "#rooty",
  ...
}).$mount("#rooty");
like image 633
Konrad Viltersten Avatar asked Dec 06 '16 14:12

Konrad Viltersten


1 Answers

As it seems from the documentation, purpose of $mount() is to have an unmounted vue instance and mount it later. From the docs:

If a Vue instance didn’t receive the el option at instantiation, it will be in “unmounted” state, without an associated DOM element. vm.$mount() can be used to manually start the mounting of an unmounted Vue instance.


I believe el:"#rooty" is just a syntactic sugar provided to users over $mount as internally $mount is used to attach an instance to HTML element. see the code below from vue repo:

export function initRender (vm: Component) {
  ...
  ...
  // bind the createElement fn to this instance
  // so that we get proper render context inside it.
  // args order: tag, data, children, needNormalization, alwaysNormalize
  // internal version is used by render functions compiled from templates
  vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
  // normalization is always applied for the public version, used in
  // user-written render functions.
  vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)
  if (vm.$options.el) {
    vm.$mount(vm.$options.el)
  }
}
like image 152
Saurabh Avatar answered Oct 13 '22 00:10

Saurabh