5

Vue のインスタンスを HTML 要素にアタッチするには、2 つの方法があります。

  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");
4

1 に答える 1

4

ドキュメントから見えるように、の目的は$mount()、マウントされていない vue インスタンスを作成し、後でマウントすることです。ドキュメントから:

Vue インスタンスがインスタンス化時に el オプションを受け取らなかった場合、DOM 要素が関連付けられていない「マウントされていない」状態になります。vm.$mount() を使用して、マウントされていない Vue インスタンスのマウントを手動で開始できます。


インスタンスを HTML 要素にアタッチするために内部的に使用されるため、el:"#rooty"ユーザーに提供される構文糖衣にすぎないと思います。vue repoから以下のコードを参照してください。$mount$mount

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)
  }
}
于 2016-12-06T14:22:22.467 に答える