mixin混入

mixin(混入)

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

使用方式:

    第一步定义混合,例如:

            {

                      data(){.........},

                      methods:{.........}

                     ..............}

      第二步使用混入。例如

             (1)全局混入Vue.mixin(xx)

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

备注:组件中data中的数据、methods中的方法如果和mixin发生冲突【有相同的data数据、methods方法。以组件中的为主】

 

App.vue

<template>
  <div>
    <School></School>
    <Student></Student>
  </div>
</template>

<script>
import Student from "./components/Student";
import School from "./components/School";

export default {
  name: 'App',
  components: {
    Student,School
  }
}
</script>

 

mixin.js(在src目录下创建)

export const hunhe ={
    methods:{
        showName(){
        alert(this.name)
    }
},
export const hunhe2 ={
    data(){
      return{
          x:100,
          y:200 }
}
}

 

School.vue

<template>
  <div>
    <h2 @click="showName">学校名称:{{name}}</h2>
    <h2>学校地址:{{address}}</h2>
  </div>
</template>

<!--School组件引用hunhe2之前没有x,y,引用后除了name、address又增加了x,y-->
<script>
import {hunhe,hunhe2} from '../mixin'

export default {
  name: "School",
  data(){
    return{
      name:'尚硅谷',
      address:'北京'
    }
  },
  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]
}
</script>

 

上一篇:vue混入mixin的使用,保证你看的明明白白!


下一篇:Vue--混入(Mixin)