Vue -mixin混合

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),
})

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值