mixins配置项
Mixin[混合/入]:是Vue框架中一个重要的概念,它提供了一种非常灵活的方式来分发Vue组件中的可复用功能 。一个Mixin对象可以包含任意组件选项 ,如data、methods、created等。当一个组件使用Mixin对象时,所有Mixin对象的选项将被"混合"进入该组件本身的选项中。
功能 :可以把多个组件共用的配置提取成一个混入对象。整合后作为公共配置,供多个组件使用。
Mixin的使用
在Vue中,Mixin的使用分为两种情况:局部混入 和全局混入 。
局部混入是指在需要的组件中引入Mixin,而全局混入则意味着在任何组件中都可以使用Mixin。
说明:
1、如果同一个配置【生命钩子除外】组件中有,混合中也有,那以【组件中的】为主。
2、如果同一个生命钩子,组件中有,混合中也有,那么双方的钩子都会执行 ,而且同一个生命钩子先执行【混合中的】。
使用方式:
第一步:定义混合,例如:
javascript
{
data(){...},
methods:{...}
...
}
第二部:使用混合,例如:
(1).局部混入:
javascript
mixins:['xxx']
(2).全局混入:
javascript
Vue.mixin(xxx)
举例:SchoolList.vue
html
<template>
<div>
<h2 @click="showName" class="tip">学校名称:{{ name }}</h2>
<h2>学校地址:{{ address }}</h2>
</div>
</template>
<script>
// 引入mixin.js中的a、b、c 对象
import { a, b, c } from "../mixin";
export default {
name: "SchoolList",
data() {
return {
name: "南昌大学",
address: "南昌市红谷滩新区",
};
},
// 使对象a、b、c混合。供组件使用。【局部混合】
mixins: [a, b, c],
// SchoolList组件和StudentList组件,methods配置项代码一样,可以进行混合(mixin),把这部分代码放入mixin.js(可以自定义命名)中。实现代码复用。
// methods: {
// showName() {
// alert(this.name);
// }
// }
};
</script>
<style>
.tip {
background-color: darkorange;
}
</style>
StudentList.vue
html
<template>
<div>
<h2 @click="showName" class="tip">学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
</div>
</template>
<script>
// 引入mixin.js文件中的a、b、c 对象
import { a, b, c } from "../mixin";
export default {
name: "StudentList",
data() {
return {
name: "张三",
sex: "男",
};
},
// 使对象a、b、c混合。供组件使用。【局部混合】
mixins: [a, b, c],
// SchoolList组件和StudentList组件,methods配置项代码一样,可以进行混合(mixin),把这部分代码放入mixin.js(可以自定义命名)中。实现代码复用。
// methods: {
// showName() {
// alert(this.name);
// },
// }
};
</script>
<style>
.tip {
background-color: darkcyan;
}
</style>
mixin.js
javascript
// 分别暴露
export const a = {
methods: {
showName() {
alert(this.name);
}
}
}
// 分别暴露
export const b = {
mounted() {
console.log("你好啊!")
console.log(this.x);
console.log(this.y);
}
}
// 分别暴露
export const c = {
data() {
return {
x: 100,
y: 200
}
}
}
App.vue
html
<template>
<div>
<SchoolList />
<hr>
<StudentList />
</div>
</template>
<script>
import SchoolList from './components/SchoolList.vue';
import StudentList from './components/StudentList.vue';
export default {
name:'App',
components:{SchoolList,StudentList},
}
</script>
<style>
</style>
main.js
javascript
// 引入Vue
import Vue from "vue";
// 引入App
import App from "./App.vue";
// 关闭生产提示
Vue.config.productionTip = false;
// 引入mixin.js中的a、b、c 对象
// import { a, b, c } from "./mixin"
// 使对象a、b、c混合。供所有组件(共3个组件) + vm(共1个) 使用。【全局混合】
// Vue.mixin(a);
// Vue.mixin(b);
// Vue.mixin(c);
// 创建vm
new Vue({
el: '#app',
render: h => h(App)
})
局部混入效果:

全局混入效果:
