mixin(混入)
功能:可以把多个组件共用的配置提取成一个混入对象
使用方式:
第一步定义混合,例如:
{
data(){....},
methods:{....}
....
}
```
第二步使用混入:
全局混入:```Vue.mixin(xxx)```
局部混入:```mixins:['xxx'] ```
局部混合
mixin.js
export const hunhe = {
methods: {
showName() {
alert(this.name);
}
},
mounted() {
console.log('你好啊')
}
}
export const hunhe2 = {
data() {
return {
x :2,
y :6
}
}
}
组件中也有x,返回的值以组件为主
App.vue
<template>
<div>
<School />
<hr />
<Student />
</div>
</template>
<script>
import School from "./components/School.vue";
import Student from "./components/Student.vue";
export default {
name: "App",
components: { Student, School },
};
</script>
<style>
</style>
School.vue
<template>
<div>
<h2 @click="showName">学校名称:{{ name }}</h2>
<h2>学校地址:{{ address }}</h2>
</div>
</template>
<script>
import { hunhe,hunhe2 } from "../mixin";
export default {
name: "School",
data() {
return {
name: "华立",
address: "广州",
x:555
};
},
mounted() {
console.log("你好啊!!");
},
mixins: [hunhe,hunhe2],
};
</script>
Student.vue
<template>
<div>
<h2 @click="showName">学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
</div>
</template>
<script>
//引入一个hunhe
import {hunhe} from '../mixin'
export default {
name: "Student",
data() {
return {
name: "张三",
sex: "男",
};
},
mixins:[hunhe]
}
</script>
全局混合
main.js
//引入Vue
import Vue from 'vue'
//引入App组件,它是所有组件的父组件
import App from './App.vue'
import {hunhe,hunhe2} from './mixin'
//关闭vue的生产提示
Vue.config.productionTip = false
Vue.mixin(hunhe)
Vue.mixin(hunhe2)
new Vue({
el: '#app',
//将App组件放入容器中
render: h => h(App),
})