前端开发那些事儿

Vue Mixin用法

2020-07-13  本文已影响0人  六寸光阴丶

一、 介绍

vue中提供了一种混合机制--mixins,用来更高效的实现组件内容的复用。

二、 使用

mixin.js

export default {
  data () {
    return {
      data1: 'mixin1',
      data2: 'mixin2'
    }
  },
  computed: {
    computed1 () {
      return this.data1 + this.data2
    },
    computed2 () {
      return this.data1 + this.data3
    }
  },
  mounted () {
    console.log('mixin中的mounted')
  },
  methods: {
    handleMethod1 () {
      console.log(
        `mixin中的方法1,
        data1:${this.data1},
        computed1:${this.computed1}`
      )
    },
    handleMethod2 () {
      console.log(
        `mixin中的方法2,
        data2:${this.data2},
        computed2:${this.computed2}`
      )
    }
  }
}

index.vue

<template>
  <div></div>
</template>
<script>
// 引入mixin
import Mixin from './mixin.js'
export default {
  // 使用,放入一个数组
  mixins: [Mixin],
  data () {
    return {
      data1: 'index1',
      data3: 'index3'
    }
  },
  computed: {
    computed1 () {
      return this.data1 + this.data2
    },
    computed3 () {
      return this.data2 + this.data3
    }
  },
  mounted () {
    console.log('组件中的mounted')
    this.handleMethod1()
    this.handleMethod2()
    this.handleMethod3()
  },
  methods: {
    handleMethod1 () {
      console.log(
        `组件中的方法1,
        data1:${this.data1},
        computed1:${this.computed1}`
      )
    },
    handleMethod3 () {
      console.log(
        `组件中的方法3,
        data3:${this.data3},
        computed3:${this.computed3}`
      )
    }
  }
}
</script>

</script>

执行结果

mixin中的mounted
组件中的mounted
组件中的方法1,data1:index1,computed1:index1mixin2
mixin中的方法2,data2:mixin2,computed2:index1index3
组件中的方法3,data3:index3,computed3:mixin2index3
上一篇 下一篇

猜你喜欢

热点阅读