【问题标题】:Which is the most recommended syntax for attaching Vue object to an element?将 Vue 对象附加到元素的最推荐语法是什么?
【发布时间】:2017-04-21 04:50:40
【问题描述】:

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

  1. 通过属性引用,el:"#rooty"
  2. 通过方法调用,$mount("#rooty")

我无法在他们之间做出决定。它们是否完全等价?如果一个更新或过时,推荐哪一个?还有其他区别吗?在这种情况下,会是什么?

按属性引用。

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

通过方法调用。

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

【问题讨论】:

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


    【解决方案1】:

    从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)
      }
    }
    

    【讨论】:

    • 不错,我也看过那段话。也许我的问题措辞不当。我应该以没有未安装的实例为目标吗?我应该尝试达到相反的效果吗?有关系吗?有什么意义吗?最常见的是什么?我有我的看法,但它基于 C# 和那里的配置。
    • @KonradViltersten 我认为这并不重要,重要的是您是否有一些未安装实例的用例,您希望在不同的 HTML 元素上安装相同的组件。我已经更新了我的答案,看来 vue 内部使用 $mount 来挂载组件,$el 是为了方便用户,因为传递哈希总是很容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 2020-09-08
    • 2011-11-21
    • 2016-09-23
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    相关资源
    最近更新 更多