Browse Source

fix #612 v-html treating `#` as id selector

Evan You 11 years ago
parent
commit
2e816de71d
3 changed files with 15 additions and 6 deletions
  1. 2 1
      src/directives/html.js
  2. 7 5
      src/parsers/template.js
  3. 6 0
      test/unit/specs/parsers/template_spec.js

+ 2 - 1
src/directives/html.js

@@ -28,7 +28,8 @@ module.exports = {
       _.remove(this.nodes[i])
     }
     // convert new value to a fragment
-    var frag = templateParser.parse(value, true)
+    // do not attempt to retrieve from id selector
+    var frag = templateParser.parse(value, true, true)
     // save a reference to these nodes so we can remove later
     this.nodes = _.toArray(frag.childNodes)
     _.before(frag, this.el)

+ 7 - 5
src/parsers/template.js

@@ -1,6 +1,7 @@
 var _ = require('../util')
 var Cache = require('../cache')
-var templateCache = new Cache(100)
+var templateCache = new Cache(1000)
+var idSelectorCache = new Cache(1000)
 
 var map = {
   _default : [0, '', ''],
@@ -204,10 +205,11 @@ exports.clone = function (node) {
  *    - id selector: '#some-template-id'
  *    - template string: '<div><span>{{msg}}</span></div>'
  * @param {Boolean} clone
+ * @param {Boolean} noSelector
  * @return {DocumentFragment|undefined}
  */
 
-exports.parse = function (template, clone) {
+exports.parse = function (template, clone, noSelector) {
   var node, frag
 
   // if the template is already a document fragment,
@@ -220,15 +222,15 @@ exports.parse = function (template, clone) {
 
   if (typeof template === 'string') {
     // id selector
-    if (template.charAt(0) === '#') {
+    if (!noSelector && template.charAt(0) === '#') {
       // id selector can be cached too
-      frag = templateCache.get(template)
+      frag = idSelectorCache.get(template)
       if (!frag) {
         node = document.getElementById(template.slice(1))
         if (node) {
           frag = nodeToFragment(node)
           // save selector to cache
-          templateCache.put(template, frag)
+          idSelectorCache.put(template, frag)
         }
       }
     } else {

+ 6 - 0
test/unit/specs/parsers/template_spec.js

@@ -117,6 +117,12 @@ if (_.inBrowser) {
       document.head.removeChild(node)
     })
 
+    it('should be able to not use id selectors', function () {
+      var res = parse('#hi', false, true)
+      expect(res instanceof DocumentFragment).toBeTruthy()
+      expect(res.firstChild.nodeValue).toBe('#hi')
+    })
+
     it('should deal with Safari template clone bug', function () {
       var a = document.createElement('div')
       a.innerHTML = '<template>1</template>'