简单介绍

  • 可以把多个组件共有的数据,方法,提取成一个混合文件
  • data中数据自己和混合文件都有时,以自己的数据为主
  • 生命周期还有方法这些都是独立的

全局混合

// 这样引入所有的页面,组件都会使用这个混合
import mixin from './components/mixin/mixin'

Vue.mixin(mixin)

局部混合

// 常用引用方式
// mixin.js

export default {
    data() {
        return {
            mixData: '这是mixin中数据',
            x: 100,
        }
    },
    created () {
      console.log(this.y)
    },
    methods: {
        handleClick() {
            console.log(this.name)
        }
    },
    computed: {
        showNumber() {
            return this.x + this.y
        }
    }
}


// 两个需要引用混合的组件

// Student.vue
<template>
    <div>
      <h1>{{ msg }}</h1>
      <div @click="handleClick">姓名:{{name}}</div>
      <div>年龄:{{age}}</div>
      <div>数字:{{showNumber}}</div>
    </div>
</template>
<script>

import mixin from './mixin/mixin'

export default {
  name: 'Student',
  data () {
    return {
      msg: 'Welcome',
      y: 100
    }
  },
  mixins: [mixin],
  props: {
    name: {
      type: String,
      requried: true
    },
    age: {
      type: Number,
      default: 18
    }
  },
  created () {
    console.log(this.mixData)
  }
}
</script>


// School.vue
<template>
    <div>
      <h1>{{ msg }}</h1>
      <div @click="handleClick">姓名:{{name}}</div>
      <div>地址:{{address}}</div>
      <div>数字:{{showNumber}}</div>
    </div>
</template>
<script>

import mixin from './mixin/mixin'

export default {
  name: 'Student',
  data () {
    return {
      msg: 'Welcome',
      y: 200
    }
  },
  mixins: [mixin],
  props: {
    name: {
      type: String,
      requried: true
    },
    address: {
      type: String,
      requried: true
    }
  },
  created () {
    console.log(this.mixData)
  }
}
</script>

後來
1 声望0 粉丝

« 上一篇
Vue-props
下一篇 »
Vue组件-slot