vue之mixin理解与使用🍉

1,253 阅读2分钟

这是我参与8月更文挑战的第22天,活动详情查看:8月更文挑战

🍕 前言

  • 最近确实是有点忙,天天日更确实有点不知道写什么了,所以就把以前自己记录的文章拿出来吧。
  • 可能会有点水,大家如果有需要的可以看看。
  • mixin可以让我们的组件复用一些我们配置相同的生命周期或者方法,当然这个mixin只能在vue 2.x使用,vue 3.0已经不需要了。

🥪 使用场景

  • 当有两个非常相似的组件,除了一些个别的异步请求外其余的配置都一样,甚至父组件传的值也是一样的,但他们之间又存在着足够的差异性,这时候就不得不拆分成两个组件,如果拆分成两个组件,你就不得不冒着一旦功能变动就要在两个文件中更新代码的风险。

  • 这时候就可以使用mixin(混入)了,混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。可能听起来比较抽象,现在举个简单的例子吧。

🥧 实际案例

  • 对比这两个组件的script有什么不同和相同之处
//组件一
<script>
import { findClassHourByCurricid } from '@/api/system/class'
export default {
    name: 'AllClassHour',
    props: {
        recordDeatil: {
        type: Object,
        required: true
        },
        detailShow: {
            type: Boolean,
            require: true,
            default: false
        }
    },
    data () {
        return {
            data: [],
            columns: [
                        {
                            title: '序号',
                            dataIndex: 'index',
                            key: 'index',
                            align: 'center',
                            width: '10%',
                            customRender: (text, record, index) => `${index + 1}`
                        },
                        {
                            dataIndex: 'classname',
                            title: '课时名称',
                            key: 'classname',
                            width: '50%',
                            // align: 'center',
                            scopedSlots: { customRender: 'classname' }
                        },
                        {
                            title: '创建日期',
                            dataIndex: 'crtime',
                            key: 'crtime',
                            width: '50%',
                            // align: 'center',
                            scopedSlots: { customRender: 'crtime' }
                        }
                    ],
            pagination: false,
            loading: false,
            status: false
        }
    },
    mounted () {
    this.getClassHour()
        this.test()
    },

    methods: {
        test () {
            console.log('测试公共组件')
        },
        getClassHour () {
            this.data = []
            const params = {
                curricid: this.recordDeatil.curricid
            }
            this.loading = true
            findClassHourByCurricid(params).then(res => {
                const classHourDetail = res.data.data
                this.data = classHourDetail
                this.loading = false
                }
            )
        }
    }
}

</script>
//组件二
<script>
import { findStudentByCurricid } from '@/api/system/class'
export default {
    name: 'AllStudent',
    props: {
        recordDeatil: {
        type: Object,
        required: true
        },
        detailShow: {
            type: Boolean,
            require: true,
            default: false
        }
    },
    data () {
        return {
            data: [],
            columns: [
                        {
                            title: '序号',
                            dataIndex: 'index',
                            key: 'index',
                            align: 'center',
                            width: '10%',
                            customRender: (text, record, index) => `${index + 1}`
                        },
                        {
                            dataIndex: 'truename',
                            title: '真实姓名',
                            key: 'truename',
                            width: '50%',
                            // align: 'center',
                            scopedSlots: { customRender: 'truename' }
                        },
                        {
                            title: '中文名',
                            dataIndex: 'chanema',
                            width: '50%',
                            // align: 'center',
                            key: 'chanema'
                        }
                    ],
            pagination: false,
            loading: false,
            status: false
        }
    },
    mounted () {
        this.getStudent()
        this.test()
    },
    methods: {
        test () {
            console.log('测试公共组件')
        },
        getStudent () {
            this.data = []
            const params = {
                curricid: this.recordDeatil.curricid
            }
            this.loading = true
            findStudentByCurricid(params).then(res => {
                const studentDetail = res.data.data
                this.data = studentDetail
                this.loading = false
                }
            )
        }
    }
}

</script>

可以发现,除了获取表格的数据所调用的异步请求外其余配置基本上相同 于是我们可以在这里提取逻辑并创建可以被重用的项:

export const publish = {
    props: {
        recordDeatil: {
        type: Object,
        required: true
        },
        detailShow: {
            type: Boolean,
            require: true,
            default: false
        }
    },
    data () {
        return {
            data: [],
            pagination: false,
            loading: false,
            status: false
        }
    },
    methods: {
        test () {
            console.log('测试公共方法')
        }
    }
}
  • 然后我们把组件中重复的配置和方法全部去掉,引用这个mixin

  • 运行代码会发现 结果是一样的

  • 即便我们使用的是一个对象而不是一个组件,生命周期函数对我们来说仍然是可用的,理解这点很重要。我们也可以这里使用mounted()钩子函数,它将被应用于组件的生命周期上。这种工作方式真的很灵活也很强大。

👋 写在最后

  • 在一些我们需要做同样配置或者相似度极高的组件时,我们不妨可以试试Mixin混入你所需要的相同配置或者方法,这样会使我们的开发效率大大提高。
  • 当然这个mixin只适用于vue 2.x,vue 3.0Composition API已经很强大了。

🌅 往期精彩

一文搞定echarts地图轮播高亮⚡

看完还分不清重绘和重排过来捶我👊,我说的!!!

如何优雅的使用Vuepress编写组件示例(上)👈

如何优雅的使用Vuepress编写组件示例(下)👈