---
title: 混合
type: guide
order: 16
---
## 基礎
混合以一種靈活的方式為組件提供分布復用功能。混合對象可以包含任意的組件選項。當組件使用了混合對象時,混合對象的所有選項將被“混入”組件自己的選項中。
示例:
``` js
// 定義一個混合對象
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// 定義一個組件,使用這個混合對象
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // -> "hello from mixin!"
```
## 選項合并
當混合對象與組件包含同名選項時,這些選項將以適當的策略合并。例如,同名鉤子函數被并入一個數組,因而都會被調用。另外,混合的鉤子將在組件自己的鉤子**之前**調用。
``` js
var mixin = {
created: function () {
console.log('mixin hook called')
}
}
new Vue({
mixins: [mixin],
created: function () {
console.log('component hook called')
}
})
// -> "mixin hook called"
// -> "component hook called"
```
值為對象的選項,如 `methods`, `components` 和 `directives` 將合并到同一個對象內。如果鍵沖突則組件的選項優先。
``` js
var mixin = {
methods: {
foo: function () {
console.log('foo')
},
conflicting: function () {
console.log('from mixin')
}
}
}
var vm = new Vue({
mixins: [mixin],
methods: {
bar: function () {
console.log('bar')
},
conflicting: function () {
console.log('from self')
}
}
})
vm.foo() // -> "foo"
vm.bar() // -> "bar"
vm.conflicting() // -> "from self"
```
注意 `Vue.extend()` 使用同樣的合并策略。
## 全局混合
也可以全局注冊混合。小心使用!一旦全局注冊混合,它會影響**所有**之后創建的 Vue 實例。如果使用恰當,可以為自定義選項注入處理邏輯:
``` js
// 為 `myOption` 自定義選項注入一個處理器
Vue.mixin({
created: function () {
var myOption = this.$options.myOption
if (myOption) {
console.log(myOption)
}
}
})
new Vue({
myOption: 'hello!'
})
// -> "hello!"
```
## 自定義選項合并策略
在合并自定義選項時,默認的合并策略是簡單地覆蓋已有值。如果想用自定義邏輯合并自定義選項,則向 `Vue.config.optionMergeStrategies` 添加一個函數:
``` js
Vue.config.optionMergeStrategies.myOption = function (toVal, fromVal) {
// 返回 mergedVal
}
```
對于多數值為對象的選項,可以簡單地使用 `methods` 所用的合并策略:
``` js
var strategies = Vue.config.optionMergeStrategies
strategies.myOption = strategies.methods
```
- vue
- 官方教程
- 起步
- 安裝
- 概述
- Vue 實例
- Class 與 Style 綁定
- 數據綁定語法
- 條件渲染
- 列表渲染
- 表單控件綁定
- 組件
- 計算屬性
- 自定義指令
- 自定義過濾器
- 方法與事件處理器
- 混合
- 插件
- 過渡
- 深入響應式原理
- 對比其它框架
- 構建大型應用
- API
- vue-router
- 安裝
- 基本用法
- 嵌套路由
- 路由對象和路由匹配
- 具名路徑
- 路由配置項
- router-view
- v-link
- 切換控制流水線
- 切換鉤子函數
- data
- activate
- deactivate
- canActivate
- canDeactivate
- canReuse
- API
- 路由實例屬性
- router.start
- router.stop
- router.map
- router.on
- router.go
- router.replace
- router.redirect
- router.alias
- router.beforeEach
- router.afterEach
- 文章
- VUE.JS: A (RE)INTRODUCTION
- 源碼
- 表單控件綁定