vue 封装对象深拷贝方法

  1. 在 src/ utils文件夹下面新建index.js
// index.js// 深拷贝对象export function deepClone(obj) {const _toString = Object.prototype.toString// null, undefined, non-object, functionif (!obj || typeof obj !== 'object') {return obj}// DOM Nodeif (obj.nodeType && 'cloneNode' in obj) {return obj.cloneNode(true)}// Dateif (_toString.call(obj) === '[object Date]') {return new Date(obj.getTime())}// RegExpif (_toString.call(obj) === '[object RegExp]') {const flags = []if (obj.global) { flags.push('g') }if (obj.multiline) { flags.push('m') }if (obj.ignoreCase) { flags.push('i') }return new RegExp(obj.source, flags.join(''))}const result = Array.isArray(obj) ? [] : obj.constructor ? new obj.constructor() : {}for (const key in obj) {result[key] = deepClone(obj[key])}return result}
  1. 使用
// 简单使用<script>import { deepClone } from '@/utils/index'export default {name: "HomeView",data() {return {obj: {a: 1,b: 2,c: 3,},};},mounted(){let newObj = deepClone(this.obj) // 方法使用// 方法验证console.log(newObj)// {a: 1, b: 2, c: 3}newObj.c = 4console.log(newObj) // {a: 1, b: 2, c: 4}console.log(this.obj)// {a: 1, b: 2, c: 3}}};</script>
  1. 搞定 复制可直接用!