mixin: 有两个很是类似的组件,他们的基本功能是同样的,能够局注册一个混合,影响注册以后vue
全部建立的每一个 Vue 实例,这就是mixin。vue-cli
Mixin对编写函数式风格的代码颇有用,通常状况下不会改变函数做用域外部的任何东西,输入相同,获得的结果也必定相同。函数
新建一个mixin.js 文件,this
minix.js export const myminix= { data(){ return { } }, mounted(){ this.sayhello(); }, created(){ }, methods:{ sayhello:function(){ console.log("hello from myMinix!"); } } }
一个简单的方法,在组件被挂载后 输出 “hello”,code
而后在想要使用这个公共方法的组件中引入进去。ip
other.vue script: export default { mixins:[myminix], }
这样引入后的效果,就是在other的组件中,一样加入了sayhello() 方法作用域
other.vue script: export default { mounted(){ this.sayhello(); }, methods:{ sayhello:function(){ console.log("hello from myMinix!"); } } //output 'hello from myMinix'
在other 组件被挂载后,输出hello from myMinix,io
到这里,会有一个问题,若是other.vue 自己也有一样是操做挂载在mounted 上,到底谁会先执行,console
other.vue script: export default { mixins:[myminix], mounted(){ this.sayhello(); }, methods:{ sayhello:function(){ console.log("hello from other instance!"); } } //output 'hello from myMinix' //output 'hello from myMinix'
输出了两次同样的结果,都来自other 组件, 第一个函数被调用时,没有被销毁,它只是被重写了。咱们在这里调用了两次sayhello()函数。function
好比在 vue-cli 构建的项目中,main.js 中定义了一个minix,而且挂载在vue 实例上,
Vue.mixin({ mounted() { console.log("hello from other"); } }) new Vue({ })
那么在 Vue 实例下的每一个组件都会 在挂载的时候执行一次这个方法,输出屡次 “hello from other”