1 简介
混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。
简单来说,就是把组件的某些配置可以抽取出来,达到复用的效果。比如几个组件都用到一个方法,就可以把这个方法抽取出来,放到mixin里面,几个组件引用即可
2 混入的作用
多个组件可以共享数据和方法,在使用mixin的组件中引入后,mixin中的方法和属性也就并入到该组件中,可以直接使用。
如果minxin和组件中的配置重复了,采用mixin的配置(勾子函数例外)。mixin和组件中配置了同一个勾子函数,两个钩子函数都被调用,mixin中的钩子首先执行。
3 使用
3.1 定义混入
const mixin = {
data() {....},
methods: {....}
....
}
3.2 使用混入
局部使用混入
mixins:['xxx']
3.3 全局混入
Vue.mixin('xxx')
4 示例
1)mixin.js,里面定义了两个混入
export const hunhe = {
methods: {
showName(){
alert('hahaha')
}
},
mounted() {
console.log('混入的mounted函数调用!')
},
}
export const hunhe2 = {
data() {
return {
x:100,
y:200
}
},
}
2)StudentComp.vue
引入使用了两个混入,使用了x和y两个属性以及showName函数
<template>
<div>
<h1>{{stname}}</h1>
<h1>{{age + 1}}</h1>
<h1>{{x + y}}</h1>
<button v-on:click="showName">点击</button>
</div>
</template>
<script>
import {hunhe,hunhe2} from '../mixin.js'
export default {
name:'StudentComp',
data(){
return {
}
},
props: {
stname: {
type: String, // 类型
required: true,// 必要性
default: 'cess'// 默认值
},
age:{
type: Number, // 类型
required: true,// 必要性
default: 18// 默认值
}
},
mixins:[hunhe,hunhe2],
mounted() {
console.log('StudentComp的mounted调用')
},
}
</script>
3) SchoolComp.vue
<template>
<div>
<h1 >{{schoolname}}</h1>
<StudentComp stname="学生" :age="age" ></StudentComp>
</div>
</template>
<script>
import StudentComp from './StudentComp'
export default {
name:'SchoolComp',
data(){
return {
schoolname:'实验小学1',
age:18
}
},
components:{
StudentComp
}
}
</script>
<style>
</style>
4)app.vue
<template>
<div>
<SchoolComp></SchoolComp>
</div>
</template>
<script>
import SchoolComp from './components/SchoolComp'
export default {
name:'App',
components:{
SchoolComp
}
}
</script>
5) 效果
先看控制台:两个mounted函数都调用了,且混入的先调用
x+y=300在页面显示了
showName函数也正常调用