瀏覽代碼

v-for iterator syntax

Evan You 10 年之前
父節點
當前提交
50efdc5799
共有 2 個文件被更改,包括 17 次插入5 次删除
  1. 2 1
      src/compiler/codegen/index.js
  2. 15 4
      src/compiler/parser/index.js

+ 2 - 1
src/compiler/codegen/index.js

@@ -40,8 +40,9 @@ function genElse (el) {
 function genFor (el) {
   const exp = el.for
   const alias = el.alias
+  const iterator = el.iterator || '$index'
   el.for = false // avoid recursion
-  return `(${exp})&&(${exp}).map(function(${alias},$index) {return ${genElement(el)}})`
+  return `(${exp})&&(${exp}).map(function(${alias},${iterator}) {return ${genElement(el)}})`
 }
 
 function genData (el) {

+ 15 - 4
src/compiler/parser/index.js

@@ -9,7 +9,8 @@ const onRE = /^@|^v-on:/
 const argRE = /:(.*)$/
 const modifierRE = /\.[^\.]+/g
 const mustUsePropsRE = /^(value|selected|checked|muted)$/
-const forAliasRE = /([a-zA-Z_][\w]*)\s+(?:in|of)\s+(.*)/
+const forAliasRE = /(.*)\s+(?:in|of)\s+(.*)/
+const forIteratorRE = /\((.*),(.*)\)/
 const camelRE = /[a-z\d][A-Z]/
 
 // this map covers SVG elements that can appear as template root nodes
@@ -161,11 +162,21 @@ function processFor (el) {
   let exp
   if ((exp = getAndRemoveAttr(el, 'v-for'))) {
     const inMatch = exp.match(forAliasRE)
-    if (process.env.NODE_ENV !== 'production' && !inMatch) {
-      warn(`Invalid v-for expression: ${exp}`)
+    if (!inMatch) {
+      process.env.NODE_ENV !== 'production' && warn(
+        `Invalid v-for expression: ${exp}`
+      )
+      return
     }
-    el.alias = inMatch[1].trim()
     el.for = inMatch[2].trim()
+    const alias = inMatch[1].trim()
+    const iteratorMatch = alias.match(forIteratorRE)
+    if (iteratorMatch) {
+      el.iterator = iteratorMatch[1].trim()
+      el.alias = iteratorMatch[2].trim()
+    } else {
+      el.alias = alias
+    }
     if ((exp = getAndRemoveAttr(el, 'track-by'))) {
       el.key = exp === '$index'
         ? exp