Преглед изворни кода

input attr bindings are bound as v-model

Evan You пре 11 година
родитељ
комит
22c31e54bf
2 измењених фајлова са 50 додато и 31 уклоњено
  1. 26 6
      src/compile/compile.js
  2. 24 25
      src/directives/attr.js

+ 26 - 6
src/compile/compile.js

@@ -462,12 +462,32 @@ function collectAttrDirective (el, name, value, options) {
         'in attribute bindings.'
       )
     } else {
-      var descriptors = dirParser.parse(tokens[0].value)
-      descriptors[0].arg = name
-      return {
-        name: 'attr',
-        def: options.directives.attr,
-        descriptors: descriptors
+      value = tokens[0].value
+      var descriptors
+      if (
+        name === 'value' ||
+        name === 'selected' ||
+        name === 'checked'
+      ) {
+        // special input attributes are bound as v-model
+        descriptors = dirParser.parse(value)
+        // remove attribute so v-model uses vm data as
+        // initial value
+        el.removeAttribute(name)
+        return {
+          name: 'model',
+          def: options.directives.model,
+          descriptors: descriptors
+        }
+      } else {
+        // normal attribute.
+        value = name + ':' + value
+        descriptors = dirParser.parse(value)
+        return {
+          name: 'attr',
+          def: options.directives.attr,
+          descriptors: descriptors
+        }
       }
     }
   }

+ 24 - 25
src/directives/attr.js

@@ -7,34 +7,33 @@ var namespaces = {
 module.exports = {
 
   bind: function () {
-    // check namespaced attributes
-    if (this.el.namespaceURI.slice(-3) === 'svg') {
-      var name = this.arg
-      var colonIndex = name.indexOf(':')
-      if (colonIndex > 0) {
-        this.localName = name.slice(colonIndex + 1)
-        this.namespace = namespaces[name.slice(0, colonIndex)]
-      }
-    }
-  },
-
-  update: function (value) {
-    var el = this.el
-    var ns = this.namespace
     var name = this.arg
-    if (value || value === 0) {
-      if (ns) {
-        el.setAttributeNS(ns, name, value)
-      } else {
-        el.setAttribute(name, value)
-      }
+    var colonIndex = name.indexOf(':')
+    // check namespaced attributes
+    if (colonIndex > 0) {
+      this.localName = name.slice(colonIndex + 1)
+      this.namespace = namespaces[name.slice(0, colonIndex)]
+      this.update = namespaceHandler
     } else {
-      if (ns) {
-        el.removeAttributeNS(ns, this.localName)
-      } else {
-        el.removeAttribute(name)
-      }
+      this.update = defaultHandler
     }
   }
 
+}
+
+function defaultHandler (value) {
+  if (value != null) {
+    this.el.setAttribute(this.arg, value)
+  } else {
+    this.el.removeAttribute(this.arg)
+  }
+}
+
+function namespaceHandler (value) {
+  var ns = this.namespace
+  if (value != null) {
+    this.el.setAttributeNS(ns, this.arg, value)
+  } else {
+    this.el.removeAttributeNS(ns, this.localName)
+  }
 }