Przeglądaj źródła

support binding v-model to alias

Evan You 10 lat temu
rodzic
commit
ade9d0548c
2 zmienionych plików z 21 dodań i 8 usunięć
  1. 4 0
      src/directives/for.js
  2. 17 8
      src/watcher.js

+ 4 - 0
src/directives/for.js

@@ -177,11 +177,15 @@ module.exports = {
     // make sure point $parent to parent scope
     scope.$parent = parentScope
     scope.$alias = alias
+    scope.$source = this.rawValue
     // define scope properties
     _.defineReactive(scope, alias, value)
     _.defineReactive(scope, '$index', index)
     if (key) {
       _.defineReactive(scope, '$key', key)
+    } else if (scope.$key) {
+      // avoid accidental fallback
+      _.define(scope, '$key', null)
     }
     var frag = this.factory.create(host, scope)
     frag.forId = this.id

+ 17 - 8
src/watcher.js

@@ -144,14 +144,23 @@ Watcher.prototype.set = function (value) {
       )
     }
   }
-  if (process.env.NODE_ENV !== 'production' &&
-      scope.$alias === this.expression) {
-    _.warn(
-      'It seems you are using two-way binding on a v-for ' +
-      'alias. This will not affect the original array. ' +
-      'Use an array of objects and bind to an object ' +
-      'property instead.'
-    )
+  // two-way sync for v-for alias
+  if (scope.$alias === this.expression) {
+    if (this.filters) {
+      process.env.NODE_ENV !== 'production' && _.warn(
+        'It seems you are using two-way binding on ' +
+        'a v-for alias, and the v-for is also filtered. ' +
+        'This will not work properly. Please use an ' +
+        'array of objects and bind to object properties ' +
+        'instead.'
+      )
+      return
+    }
+    if (scope.$key) { // original is an object
+      scope.$source[scope.$key] = value
+    } else {
+      scope.$source.$set(scope.$index, value)
+    }
   }
 }