Evan You пре 11 година
родитељ
комит
04702cd5e2
3 измењених фајлова са 44 додато и 4 уклоњено
  1. 16 0
      changes.md
  2. 12 4
      src/util/merge-option.js
  3. 16 0
      test/unit/specs/util/merge-option_spec.js

+ 16 - 0
changes.md

@@ -109,6 +109,22 @@ By default, all child components **DO NOT** inherit the parent scope. Only anony
   1. bind to parent scope properties in the component template
   2. directly access parent properties on the component instance itself, via prototypal inheritance.
 
+- #### new option: `mixins`.
+
+  The `mixins` option accepts an array of mixin objects. These mixin objects can contain instance options just like normal instance objects, and they will be merged against the eventual options using the same merge logic in `Vue.extend`. e.g. If your mixin contains a `created` hook and the component itself also has one, both functions will be called.
+
+  ``` js
+  var mixin = {
+    created: function () { console.log(2) }
+  }
+  var vm = new Vue({
+    created: function () { console.log(1) },
+    mixins: [mixin]
+  })
+  // -> 1
+  // -> 2
+  ```
+
 - #### removed options:
 
   > Breaking

+ 12 - 4
src/util/merge-option.js

@@ -199,16 +199,24 @@ module.exports = function mergeOptions (parent, child, vm) {
   var options = {}
   var key
   for (key in parent) {
-    merge(key)
+    merge(parent[key], child[key], key)
   }
   for (key in child) {
     if (!(parent.hasOwnProperty(key))) {
-      merge(key)
+      merge(parent[key], child[key], key)
     }
   }
-  function merge (key) {
+  var mixins = child.mixins
+  if (mixins) {
+    for (var i = 0, l = mixins.length; i < l; i++) {
+      for (key in mixins[i]) {
+        merge(options[key], mixins[i][key], key)
+      }
+    }
+  }
+  function merge (parentVal, childVal, key) {
     var strat = strats[key] || defaultStrat
-    options[key] = strat(parent[key], child[key], vm, key)
+    options[key] = strat(parentVal, childVal, vm, key)
   }
   return options
 }

+ 16 - 0
test/unit/specs/util/merge-option_spec.js

@@ -191,4 +191,20 @@ describe('Util - Option merging', function () {
     expect(res.data.b).toBe(2)
   })
 
+  it('mixins', function () {
+    var a = {}, b = {}, c = {}, d = {}
+    var mixinA = { a: 1, directives: { a: a } }
+    var mixinB = { b: 1, directives: { b: b } }
+    var res = merge(
+      { a: 2, directives: { c: c } },
+      { directives: { d: d }, mixins: [mixinA, mixinB] }
+    )
+    expect(res.a).toBe(1)
+    expect(res.b).toBe(1)
+    expect(res.directives.a).toBe(a)
+    expect(res.directives.b).toBe(b)
+    expect(res.directives.c).toBe(c)
+    expect(res.directives.d).toBe(d)
+  })
+
 })