mixin混入

169 阅读1分钟

1.准备

建立一个MySchool组件和一个MyStudent组件 image.png image.png

分别点击学校名和学生姓名 image.png

会弹出对应的名字 image.png image.png

2.功能:可以把多个组件共用的配置提取成一个混入对象

因为两个组件用到的方法一样,那么我们通过mixin就可以只写一遍

3.使用方式:

第一步定义混合,例如:
{
data(){....}
methods:{....}
....
}

第二步使用混入,例如:

(1).局部混入:mixins:['xxx']

1.重新建立一个js文件
image.png

2.把方法写到文件中
image.png

3.在组件中引入(两个文件都是同样操作) image.png

4.页面同样实现了点击效果 image.png

不止是methods配置项可以,其它的配置项也可以
image.png image.png

数据也可以
image.png image.png

他会和原来的数据进行一个整合
image.png

如果原来的数据也有个x
image.png

它会以原来的那个为主 image.png

但是如果是生命周期,则两个都要 image.png image.png image.png

(2).全局混入:Vue.mixin(xxx)

上面是局部混入,现在来写全局混入

把两个组件的这些引入先注释掉 image.png

在main.js文件中
image.png

引入,打入这些代码
image.png

这样也实现了 image.png

题外话:上面为什么会被挂载四次,因为下面这个有四个,一个挂载一次 image.png image.png image.png image.png image.png

这小结用到的代码: MySchool.vue

<template>
  <div class="demo">
    <h1 @click="ShowName">学校名:{{ name }}</h1>
    <h1>学校地址:{{ address }}</h1>
  </div>
</template>

<script>
// import { hunhe, hunhe2 } from "../mixin/mixin";

// 组件交互相关的代码(数据、方法等等)
export default {
  name: "MySchool",
  data() {
    return {
      name: "南京大学",
      address: "南京",
      x: 666,
    };
  },
  // mixins: [hunhe, hunhe2],
  // mounted() {
  //   console.log("学校我被挂载了");
  // },
};
</script>
MyStudent.vue
<template>
  <div class="demo">
    <h1 @click="ShowName">学校姓名:{{ name }}</h1>
    <h1>学生年龄:{{ age }}</h1>
  </div>
</template>

<script>
// import { hunhe } from "../mixin/mixin";

// 组件交互相关的代码(数据、方法等等)
export default {
  name: "MyStudent",
  data() {
    return {
      name: "张三",
      age: 18,
    };
  },
  // mixins: [hunhe],
};
</script>
App.vue
<template>
  <div>
    <School />
    <hr>
    <Student />
  </div>
</template>

<script>
// 引入组件
import School from "./components/MySchool.vue";
import Student from "./components/MyStudent.vue";

export default {
  name: "App",
  components: { School, Student },
  data() {
    return {};
  },
};
</script>
main.js
import Vue from 'vue'
import App from './App.vue'
import {hunhe,hunhe2} from './mixin.js'
Vue.config.productionTip = false
Vue.mixin(hunhe)
Vue.mixin(hunhe2)
new Vue({
    render: h => h(App)
}).$mount('#app')
mixin.js
export const hunhe = {
    methods: {
        ShowName() {
            alert(this.name);
        },
    },
    mounted(){
        console.log('我被挂载了');
    }
}

export const hunhe2 ={
    data() {
        return {
            x:1,
            y:2
        }
    },

}