mixin 混入

185 阅读1分钟

基本介绍

  • 功能:将多个组件共用的配置,提取出来,组成一个混入对象

  • mixin 混入的路径

image.png

定义混入

```
{
    data() {...},
    methods() {...}
    ...
}
```

引入并使用混入

```
// 全局使用  在App.vue文件
import {xxx} from './mixin.js'
Vue.mixin(xxx)
​
// 局部使用  在对应的Vue组件
import {xxx} from '../mixin.js'
mixins: [xxx]
```

代码实现

mixin.js 文件

```
// 分别暴露
export const mixin = {
    methods: {
        showName() {
            alert(this.name)
        }
    }
}
​
export const hello = {
    data() {
        return {
            hello: 'Hello world'
        }
    }
}
​
// 默认暴露
// export default mixin 
```

App.vue 文件

```
<template>
  <div>
    <School></School>
    <Student></Student>
  </div>
</template><script>
import School from './components/School.vue'
import Student from './components/Student.vue'export default {
  name: 'App',
  components: {
    School,
    Student
  }
}
</script>
```

School.vue 文件

```
<template>
    <div class="container">
        <h2>{{hello}}</h2>
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
        <button @click="showName">点我输出姓名</button>
    </div>
</template><script>
// 引入一个 mixin混入
import {mixin, hello} from '../mixin'// 对外暴露
export default {
    name: 'School',
    data() {
        return {
            name: '东莞理工',
            address: '东莞松山湖'
        }
    },
    mixins: [mixin, hello]
}
</script>
```

Student.vue 文件

```
<template>
  <div class="container">
    <h2>{{hello}}</h2>
    <h2>学生姓名:{{name}}</h2>
    <h2>学生年龄:{{age}}</h2>
    <button @click="showName">点我输出姓名</button>
  </div>
</template><script>
// 引入一个 mixin混入
import {mixin, hello} from '../mixin'export default {
    name: 'Student',
    data() {
      return {
        name: 'tom',
        age: 19
      }
    },
    mixins: [mixin, hello]
}
</script>
```