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

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

  • From the el property link: "# rooty"
  • By calling the $ mount method ("# rooty")

I can’t decide between them. Are they exactly equivalent? If someone is newer or outdated, which one is recommended? Is there any other difference, in that case, what would it be?

By link properties.

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

By method call.

 const app = new Vue({ store, router, //el: "#rooty", ... }).$mount("#rooty"); 
+5
source share
1 answer

As the documentation suggests, the goal of $mount() is to have an unmounted vue instance and install later. From the docs:

If the Vue instance did not receive the el parameter when creating the instance, it will be in the "unmounted" state without the associated DOM element. vm. $ mount () can be used to manually start the installation of an unmounted Vue instance.


I believe el:"#rooty" is just syntactic sugar provided to users over $mount , because $mount used internally to attach an instance to an HTML element. see code below 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) } } 
+4
source

Source: https://habr.com/ru/post/1260877/


All Articles