mixins(混入)就是定义了一部分公共的方法、计算属性或者钩子函数等 vue 组件中的可复用功能,然后混合进各个组件中使用。下面我们具体来看看怎么使用。

创建一个 demo.js 文件,然后 export 给外部使用

export const demoMixins = {
    data() {
        return {
            name: '我是 mixins 中的字符串 name',
            user: '我是 mixins 中的字符串 user'
        }
    },
    created() {
        console.log('我是 mixins 中的钩子函数 created')
        this.hello()
        this.say()
        this.pay()
    },
    methods: {
        hello() {
            console.log('我是 mixins 中的函数 hello')
        },
        say() {
            console.log('我是 mixins 中的函数 say')
        }
    }
}

在组件中引入这个 mixins 对象

<template>
    <div></div>
</template>

<script>
import { demoMixins } from '@/mixins/demo'
export default {
    mixins: [demoMixins],
    data() {
        return {
            name: '我是组件中的字符串 name',
            sex: '我是组件中的字符串 sex'
        }
    },
    created() {
        console.log('我是组件中的钩子函数 created')
        this.hello()
        this.say()
        this.pay()
    },
    methods: {
        hello() {
            console.log('我是组件中的函数 hello')
        },
        pay() {
            console.log('我是组件中的函数 pay')
        }
    }
}
</script>

我们先来看看执行结果

// => 我是 mixins 中的钩子函数 created
// => 我是组件中的函数 hello
// => 我是 mixins 中的函数 say
// => 我是组件中的函数 pay
// => 我是组件中的钩子函数 created
// => 我是组件中的函数 hello
// => 我是 mixins 中的函数 say
// => 我是组件中的函数 pay

总结

  • 混入对象的钩子将在组件自身钩子之前调用。
  • 值为对象的选项,例如 datamethodscomponentsdirectives,将被合并为同一个对象。两个对象键名冲突时,取组件对象的键值对。
  • 混入对象中可以使用和调用组件自身变量和函数,且与在组件自身中使用情况一样。

思考:一个组件是否可以同时引入多个 mixins?如果可以,执行结果和顺序又会是怎样的?大家有兴趣可以自己动手试试看。

如果觉得我的文章对你有用,请点个赞