Vue mixin 混入
功能:可以把多个组件功能的配置提取成一个混入对象,复用配置
定义混合:
{
methods: {...},
data() {...}
}
使用混合:
- 全局混合:
Vue.mixin(xxx)
- 局部混合:
mixins:['xxx']
实例
src 文件结构
|-- src
|-- App.vue
|-- main.js
|-- mixin.js
|-- components
|-- School.vue
|-- Student.vue
App.vue
<template>
<div id="app">
<School/>
<Student/>
</div>
</template>
<script>
import School from "@/components/School";
import Student from "@/components/Student";
export default {
name: 'App',
components: {
School,
Student
},
data() {
return {}
}
}
</script>
mixin.js
export const mixin1 = {
methods: {
showName() {
alert(this.name)
}
},
mounted() {
console.log('你好')
}
}
export const mixin2 = {
data() {
return {
a: 1,
b: 2
}
}
}
School.vue
<template>
<div class="school">
<h2 @click="showName">学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
<hr>
</div>
</template>
<script>
// 引入一个混合
import {mixin1} from "@/mixin";
export default {
name: 'School',
data() {
return {
name: 'ABC',
address: '长沙',
x: 100
}
},
mixins: [mixin1]
}
</script>
Student.vue
<template>
<div class="school">
<h2 @click="showName">姓名:{{name}}</h2>
<h2>性别:{{sex}}</h2>
<hr>
</div>
</template>
<script>
import {mixin1} from "@/mixin";
export default {
name: 'Student',
data() {
return {
name: '张三',
sex: '男'
}
},
mixins: [mixin1]
}
</script>