Mixins是一種分發Vue組件中可複用功能的很是靈活的一種方式
何時使用Mixins?vue
頁面的風格不用,可是執行的方法和須要的數據相似,此時應該提取出公共部分
// mixin.js數組
export const toggle = { data () { isshowing: false }, methods: { toggleShow() { this.isshowing = !this.isshowing } } }
// modal.vue
// 將mixin引入該組件,就能夠直接使用 toggleShow() 了ssh
import {mixin} from '../mixin.js' export default { mixins: [mixin], mounted () { } }
合併
當組件和混入對象含有同名選項時,這些選項將以恰當的方式混合函數
1、數據對象內
mixin的數據對象和組件的數據發生衝突時以組件數據優先this
var mixin = { data: function () { return { message: 'hello', foo: 'abc' } } } new Vue({ mixins: [mixin], data: function () { return { message: 'goodbye', bar: 'def' } }, created: function () { console.log(this.$data) // => { message: "goodbye", foo: "abc", bar: "def" } } })
2、鉤子函數
同名鉤子函數將會混合爲一個數組,都將被調用到,可是混入對象的鉤子將在組件自身鉤子以前調用code
var mixin = { created: function () { console.log('混入對象的鉤子被調用') } } new Vue({ mixins: [mixin], created: function () { console.log('組件鉤子被調用') } })
// => "混入對象的鉤子被調用"
// => "組件鉤子被調用"
3、值爲對象的選項component
值爲對象的選項,例如 methods, components 和 directives,將被混合爲同一個對象。兩個對象鍵名衝突時,取組件對象的鍵值對對象
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"
全局混入
全局混合被註冊到了每一個單一組件上。所以,它們的使用場景極其有限而且要很是的當心io
Vue.mixin({ mounted() { console.log("我是mixin"); } }) new Vue({ ... })
再次提醒,當心使用! console.log將會出如今每一個組件上console