当前位置:首页 > VUE

vue实现$.extend

2026-01-12 18:43:39VUE

实现类似 jQuery 的 $.extend 功能

在 Vue 中可以通过多种方式实现类似 jQuery 的 $.extend 功能,用于深度合并对象。以下是几种常见方法:

使用 Object.assign 进行浅合并

const obj1 = { a: 1 };
const obj2 = { b: 2 };
const merged = Object.assign({}, obj1, obj2);
// 结果: { a: 1, b: 2 }

使用展开运算符进行浅合并

const obj1 = { a: 1 };
const obj2 = { b: 2 };
const merged = { ...obj1, ...obj2 };
// 结果: { a: 1, b: 2 }

实现深度合并函数

function deepExtend(target, ...sources) {
  if (!sources.length) return target;
  const source = sources.shift();

  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        deepExtend(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return deepExtend(target, ...sources);
}

function isObject(item) {
  return item && typeof item === 'object' && !Array.isArray(item);
}

// 使用示例
const obj1 = { a: 1, nested: { x: 10 } };
const obj2 = { b: 2, nested: { y: 20 } };
const merged = deepExtend({}, obj1, obj2);
// 结果: { a: 1, b: 2, nested: { x: 10, y: 20 } }

使用 lodash 的 merge 方法

import { merge } from 'lodash';

const obj1 = { a: 1, nested: { x: 10 } };
const obj2 = { b: 2, nested: { y: 20 } };
const merged = merge({}, obj1, obj2);
// 结果: { a: 1, b: 2, nested: { x: 10, y: 20 } }

在 Vue 组件中使用 mixins

Vue 本身提供了 mixins 功能,可以用于合并组件选项:

const mixin = {
  data() {
    return {
      message: 'hello',
      foo: 'abc'
    }
  }
}

new Vue({
  mixins: [mixin],
  data() {
    return {
      message: 'goodbye',
      bar: 'def'
    }
  },
  created() {
    console.log(this.$data)
    // 结果: { message: 'goodbye', foo: 'abc', bar: 'def' }
  }
})

注意事项

  • 浅合并只处理第一层属性,深合并会递归处理所有嵌套对象
  • 数组通常不会被深度合并,而是会被覆盖
  • 使用 lodash 的 merge 函数可以处理更复杂的合并场景
  • 在 Vue 中修改响应式对象时应该使用 Vue.set 或展开运算符确保响应性

vue实现$.extend

标签: vueextend
分享给朋友:

相关文章

vue实现评论

vue实现评论

Vue 实现评论功能的方法 基础评论组件结构 使用 Vue 单文件组件(SFC)构建评论功能的核心结构。模板部分包含评论输入框和评论列表,脚本部分处理数据绑定和逻辑。 <template>…

vue实现aop切面

vue实现aop切面

Vue 实现 AOP 切面编程的方法 在 Vue 中实现 AOP(面向切面编程)可以通过多种方式,以下是几种常见的实现方法: 使用 Vue 混入(Mixins) Vue 的混入机制可以用于实现横切关…

vue实现头像剪切

vue实现头像剪切

Vue 实现头像剪切的实现方法 使用 vue-cropperjs 库 vue-cropperjs 是一个基于 cropperjs 的 Vue 组件,专门用于图片裁剪。安装方式如下: npm inst…

vue实现多选联动

vue实现多选联动

vue实现多选联动的方法 使用v-model绑定数组 在Vue中,可以通过v-model绑定一个数组来实现多选联动。当复选框被选中或取消选中时,数组会自动更新。 <template>…

vue表格实现教学

vue表格实现教学

Vue 表格实现方法 使用原生HTML表格 在Vue模板中直接使用HTML的<table>标签,结合v-for动态渲染数据: <template> <table&…

vue登录逻辑的实现

vue登录逻辑的实现

Vue 登录逻辑实现 前端实现 创建登录组件 在 Vue 项目中创建一个登录组件,通常命名为 Login.vue。该组件包含表单元素,如用户名和密码输入框,以及提交按钮。 <template…