mixin(混入),复用配置
-
功能:可以把多个组件共用的配置提取成一个混入对象
-
使用方式:
第一步定义混合:
{ data(){....}, methods:{....} .... }
第二步使用混入:
全局混入:
Vue.mixin(xxx)
局部混入:mixins:['xxx']
可以复用方法
School.vue
<template>
<div>
<h2 @click="showName">学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
//引入一个hunhe
import {hunhe} from '../mixin'
export default {
name:'School',
data() {
return {
name:'尚硅谷',
address:'北京',
x:666
}
},
mixins:[hunhe],
}
</script>
Student.vue
<template>
<div>
<h2 @click="showName">学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
</div>
</template>
<script>
import {hunhe} from '../mixin'
export default {
name:'Student',
data() {
return {
name:'张三',
sex:'男'
}
},
mixins:[hunhe]
}
</script>
mixin.js
export const hunhe = {
methods: {
showName(){
alert(this.name)
}
},
}
可以复用数据
School.vue
<template>
<div>
<h2 @click="showName">学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
//引入一个hunhe
import {hunhe} from '../mixin'
export default {
name:'School',
data() {
return {
name:'尚硅谷',
address:'北京',
x:666
}
},
mixins:[hunhe,hunhe2],
}
</script>
Student.vue
<template>
<div>
<h2 @click="showName">学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
</div>
</template>
<script>
import {hunhe} from '../mixin'
export default {
name:'Student',
data() {
return {
name:'张三',
sex:'男'
}
},
mixins:[hunhe,hunhe2]
}
</script>
mixin.js
export const hunhe = {
methods: {
showName(){
alert(this.name)
}
},
}
export const hunhe2 = {
data() {
return {
x:100,
y:200
}
},
}
全局引入