亲测有效,特此搬运

原文链接,非常感谢这位大佬的分享,救我于水火(手动比心)

Mixin 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个 mixin 对象可以包含任意组件选项。当组件使用 mixin
对象时,所有 mixin 对象的选项将被“混合”进入该组件本身的选项

  1. 新建一个文件夹用于minix,添加2方法用于混合器
    在这里插入图片描述
  2. 在main中引用全局方法
    在这里插入图片描述
    3.在局部引用mixin
    在这里插入图片描述
    代码:
<template>
    <div>
        <el-button @click="test1">全局的Minix</el-button>
        <el-button @click="test2('使用了局部mixin')">局部的Minx</el-button>
        <el-button @click="onTest">setup内部使用</el-button>
    </div>
</template>

<script>
import { getCurrentInstance } from 'vue'
import { common } from '../minix/index.js'
export default {
    name: 'Test2',
    mixins: [common],
    setup() {
        const { proxy } = getCurrentInstance()
        const onTest = () => {
            proxy.test2("setup内部使用Minx")
        }
        return {
            onTest
        }
    }

}
</script>

效果:
在这里插入图片描述

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐