Просмотр исходного кода

ensure options.el is element when initializing props

Evan You 11 лет назад
Родитель
Сommit
25eee915c7
3 измененных файлов с 28 добавлено и 13 удалено
  1. 2 8
      src/api/lifecycle.js
  2. 7 5
      src/instance/scope.js
  3. 19 0
      src/util/dom.js

+ 2 - 8
src/api/lifecycle.js

@@ -16,15 +16,9 @@ exports.$mount = function (el) {
     _.warn('$mount() should be called only once.')
     return
   }
+  el = _.query(el)
   if (!el) {
     el = document.createElement('div')
-  } else if (typeof el === 'string') {
-    var selector = el
-    el = document.querySelector(el)
-    if (!el) {
-      _.warn('Cannot find element: ' + selector)
-      return
-    }
   }
   this._compile(el)
   this._isCompiled = true
@@ -70,4 +64,4 @@ exports.$destroy = function (remove, deferCleanup) {
 
 exports.$compile = function (el, host) {
   return compiler.compile(el, this.$options, true, host)(this, el)
-}
+}

+ 7 - 5
src/instance/scope.js

@@ -27,17 +27,19 @@ exports._initProps = function () {
   var options = this.$options
   var el = options.el
   var props = options.props
-  this._propsUnlinkFn = el && props
-    ? compiler.compileAndLinkProps(
-        this, el, props
-      )
-    : null
   if (props && !el) {
     _.warn(
       'Props will not be compiled if no `el` option is ' +
       'provided at instantiation.'
     )
   }
+  // make sure to convert string selectors into element now
+  el = options.el = _.query(el)
+  this._propsUnlinkFn = el && props
+    ? compiler.compileAndLinkProps(
+        this, el, props
+      )
+    : null
 }
 
 /**

+ 19 - 0
src/util/dom.js

@@ -1,5 +1,24 @@
+var _ = require('./index')
 var config = require('../config')
 
+/**
+ * Query an element selector if it's not an element already.
+ *
+ * @param {String|Element} el
+ * @return {Element}
+ */
+
+exports.query = function (el) {
+  if (typeof el === 'string') {
+    var selector = el
+    el = document.querySelector(el)
+    if (!el) {
+      _.warn('Cannot find element: ' + selector)
+    }
+  }
+  return el
+}
+
 /**
  * Check if a node is in the document.
  * Note: document.documentElement.contains should work here