Explorar el Código

accept object values in v-class

Evan You hace 11 años
padre
commit
4e83218c0c
Se han modificado 2 ficheros con 55 adiciones y 16 borrados
  1. 35 8
      src/directives/class.js
  2. 20 8
      test/unit/specs/directives/class_spec.js

+ 35 - 8
src/directives/class.js

@@ -2,17 +2,44 @@ var _ = require('../util')
 var addClass = _.addClass
 var removeClass = _.removeClass
 
-module.exports = function (value) {
-  if (this.arg) {
-    var method = value ? addClass : removeClass
-    method(this.el, this.arg)
-  } else {
+module.exports = {
+  
+  update: function (value) {
+    if (this.arg) {
+      // single toggle
+      var method = value ? addClass : removeClass
+      method(this.el, this.arg)
+    } else {
+      this.cleanup()
+      if (value && typeof value === 'string') {
+        // raw CSSText
+        addClass(this.el, value)
+        this.lastVal = value
+      } else if (_.isPlainObject(value)) {
+        // object toggle
+        for (var key in value) {
+          if (value[key]) {
+            addClass(this.el, key)
+          } else {
+            removeClass(this.el, key)
+          }
+        }
+        this.prevKeys = Object.keys(value)
+      }
+    }
+  },
+
+  cleanup: function (value) {
     if (this.lastVal) {
       removeClass(this.el, this.lastVal)
     }
-    if (value) {
-      addClass(this.el, value)
-      this.lastVal = value
+    if (this.prevKeys) {
+      var i = this.prevKeys.length
+      while (i--) {
+        if (!value || !value[this.prevKeys[i]]) {
+          removeClass(this.el, this.prevKeys[i])
+        }
+      }
     }
   }
 }

+ 20 - 8
test/unit/specs/directives/class_spec.js

@@ -11,11 +11,10 @@ if (_.inBrowser) {
 
     it('with className', function () {
       el.className = 'haha'
-      var dir = {
+      var dir = _.extend({
         el: el,
-        arg: 'test',
-        update: def
-      }
+        arg: 'test'
+      }, def)
       dir.update(true)
       expect(el.className).toBe('haha test')
       dir.update(false)
@@ -24,10 +23,7 @@ if (_.inBrowser) {
 
     it('without className', function () {
       el.className = 'haha'
-      var dir = {
-        el: el,
-        update: def
-      }
+      var dir = _.extend({ el: el }, def)
       dir.update('test')
       expect(el.className).toBe('haha test')
       dir.update('what')
@@ -36,5 +32,21 @@ if (_.inBrowser) {
       expect(el.className).toBe('haha')
     })
 
+    it('object value', function () {
+      el.className = 'hoho'
+      var dir = _.extend({ el: el }, def)
+      dir.update({
+        a: true,
+        b: false
+      })
+      expect(el.className).toBe('hoho a')
+      dir.update({
+        b: true
+      })
+      expect(el.className).toBe('hoho b')
+      dir.update(null)
+      expect(el.className).toBe('hoho')
+    })
+
   })
 }