哪个是将Vue对象附加到元素的最推荐语法?

时间:2016-12-06 14:04:58

标签: javascript html vue.js vue-router vuex

将Vue实例附加到HTML元素时,我可以通过两种方式完成。

  1. 根据物业参考, el:"#rooty"
  2. 通过方法调用, $ mount("#rooty")
  3. 我无法在他们之间做出决定。它们是否完全相同?如果一个是新的或过时的,推荐哪一个?还有其他差异,在这种情况下会是什么?

    按物业参考。

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

    通过方法调用。

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

1 个答案:

答案 0 :(得分:4)

documentation开始,$mount()的目的是拥有一个未安装的vue实例并在以后安装它。来自文档:

  

如果Vue实例在实例化时没有收到el选项,它将处于“未安装”状态,没有关联的DOM元素。 vm。$ mount()可用于手动启动未安装的Vue实例的挂载。

我相信el:"#rooty"只是$mount以上用户提供的语法糖,因为内部$mount用于将实例附加到HTML元素。请参阅以下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)
  }
}