【 Vue 2 中的 Mixins 模式】

Vue 2 中的 Mixins 模式

在 Vue 2 里,mixins 是一种灵活的复用代码的方式,它能让你在多个组件间共享代码。借助 mixins,你可以把一些通用的选项(像 datamethodscomputed 等)封装到一个对象里,然后在多个组件中使用。

下面是 mixins 的基本使用示例:

javascript 复制代码
// 定义一个 mixin
const myMixin = {
    data() {
        return {
            mixinData: '这是 mixin 中的数据'
        }
    },
    methods: {
        mixinMethod() {
            console.log('这是 mixin 中的方法');
        }
    }
};

// 定义一个组件并使用 mixin
const MyComponent = {
    mixins: [myMixin],
    data() {
        return {
            componentData: '这是组件中的数据'
        }
    },
    methods: {
        componentMethod() {
            console.log('这是组件中的方法');
        }
    }
};

在这个例子中,MyComponent 组件使用了 myMixin,这意味着 MyComponent 能够访问 myMixin 里定义的 datamethods

选项合并规则

当组件使用 mixins 时,若组件和 mixin 存在同名选项,就需要依据一定规则进行合并:

数据对象(data

如果组件和 mixin 都定义了 data 选项,它们会递归合并。当出现键名冲突时,组件的数据会覆盖 mixin 的数据。

javascript 复制代码
const myMixin = {
    data() {
        return {
            message: 'mixin 消息'
        }
    }
};

const MyComponent = {
    mixins: [myMixin],
    data() {
        return {
            message: '组件消息'
        }
    }
};

// 创建组件实例
const vm = new Vue(MyComponent);
console.log(vm.message); // 输出: 组件消息

钩子函数

如果组件和 mixin 都定义了相同的钩子函数(如 createdmounted 等),这些钩子函数会被合并成一个数组,并且都会被调用。mixin 的钩子函数会先于组件的钩子函数执行。

javascript 复制代码
const myMixin = {
    created() {
        console.log('mixin 的 created 钩子');
    }
};

const MyComponent = {
    mixins: [myMixin],
    created() {
        console.log('组件的 created 钩子');
    }
};

// 创建组件实例
const vm = new Vue(MyComponent);
// 输出:
// mixin 的 created 钩子
// 组件的 created 钩子

方法、计算属性和 watch

如果组件和 mixin 存在同名的方法、计算属性或 watch,组件的定义会覆盖 mixin 的定义。

结合你提供的代码,MapBaseMarker.js 组件混入了 MapBaseMixin.js,两个文件里都有 init 方法。当 MapBaseMarker 组件实例化时,调用的 init 方法是 MapBaseMarker.js 文件里定义的 init 方法,而非 MapBaseMixin.js 里的 init 方法。

javascript 复制代码
// MapBaseMixin.js
const MapBaseMixin = {
    methods: {
        init() {
            console.log('MapBaseMixin 中的 init 方法');
        }
    }
};

// MapBaseMarker.js
export default {
    mixins: [MapBaseMixin],
    methods: {
        init() {
            console.log('MapBaseMarker 中的 init 方法');
        }
    }
};

// 当创建 MapBaseMarker 组件实例时,调用的 init 方法是 MapBaseMarker 中的 init 方法

综上所述,当组件和 mixin 存在同名方法时,组件自身的方法会覆盖 mixin 里的同名方法。

相关推荐
古夕32 分钟前
my-first-ai-web_问题记录03——NextJS 项目框架基础扫盲
前端·javascript·react.js
曲意已决1 小时前
《深入源码理解webpac构建流程》
前端·javascript
去伪存真1 小时前
前端如何让一套构建产物,可以部署多个环境?
前端
CC__xy1 小时前
04 类型别名type + 检测数据类型(typeof+instanceof) + 空安全+剩余和展开(运算符 ...)简单类型和复杂类型 + 模块化
开发语言·javascript·harmonyos·鸿蒙
KubeSphere1 小时前
EdgeWize v3.1.1 边缘 AI 网关功能深度解析:打造企业级边缘智能新体验
前端
小奋斗1 小时前
深入浅出:ES5/ES6+数组扁平化详解
javascript·面试
掘金安东尼2 小时前
解读 hidden=until-found 属性
前端·javascript·面试
yangholmes88882 小时前
如何为 Vue 组件提供 slots 静态类型检查
vue.js
1024小神2 小时前
jsPDF 不同屏幕尺寸 生成的pdf不一致,怎么解决
前端·javascript
滕本尊2 小时前
构建可扩展的 DSL 驱动前端框架:从 CRUD 到领域模型的跃迁
前端·全栈