欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

重置反应对象(深拷贝与浅拷贝)

最编程 2024-03-30 18:57:42
...

需求,点击不同登录方式,该图标高亮,别的图标置灰。(高亮和置灰都有相应的引入图片)

<div class="other_icon">
 <img @click="changeLoginType(item.index)" v-for="item in imgAddress" :src="item.photo" :key="item.index" />
</div>


let imgAddress = reactive([
  { photo: oneClickLoginIcon, index: 0 },
  { photo: passwordLoginIcon, index: 1 },
  { photo: phoneLoginIcon, index: 2 },
  { photo: simCardLoginIcon, index: 3 }
])

//备份
let imgAddressCopy = reactive([])
onMounted(() => {
    imgAddressCopy.push(...imgAddress) //获得备份数组
})
//重置imgAddress数组
function resetImgAddress() {
  imgAddress.length = 0
  imgAddress.push(...imgAddressCopy)
}
/**
 * 切换登录方式时图标更改
 * @param index 图标索引
 */
function changeLoginType(index) {
  resetImgAddress()
//点击不同的index,图标改变
  switch (index) {
    case 0:
      imgAddress[0].photo = oneClickLoginIconAct
      break
    case 1:
      imgAddress[1].photo = passwordLoginIconAct
      break
    case 2:
      imgAddress[2].photo = phoneLoginIconAct
      break
    case 3:
      imgAddress[3].photo = simCardLoginIconAct
      break
  }
}

此时发现点击不同的index,仍然会保留上一次的更改。

原因:

在 JavaScript 中,数组是引用类型,所以当你将 imgAddress 数组中的对象 push 到 imgAddressCopy 数组中时,实际上是将对象的引用 push 到了 imgAddressCopy 中,而不是对象的拷贝。因此,当你改变 imgAddress 数组中对象的属性时,实际上也改变了 imgAddressCopy 中对应对象的属性,因为它们引用的是同一个对象。

解决这个问题的方法是在 push 对象到 imgAddressCopy 数组中时,不要直接 push 引用,而是创建一个新的对象,以确保两个数组中的对象是独立的。这样,当你改变 imgAddress 数组中对象的属性时,不会影响 imgAddressCopy 数组中对象的属性。

let imgAddress = reactive([
  { photo: oneClickLoginIcon, index: 0 },
  { photo: passwordLoginIcon, index: 1 },
  { photo: phoneLoginIcon, index: 2 },
  { photo: simCardLoginIcon, index: 3 }
])
// 初始状态
let imgAddressCopy = reactive([])

onMounted(() => {
  //获得备份数组
  imgAddressCopy.push(...imgAddress.map(obj => ({ ...obj })))
})

function resetImgAddress() {
  imgAddress.length = 0
  imgAddress.push(...imgAddressCopy.map(obj => ({ ...obj })))
}
/**
 * 切换登录方式时图标更改
 * @param index 图标索引
 */
function changeLoginType(index) {
  resetImgAddress()
  switch (index) {
    case 0:
      imgAddress[0].photo = oneClickLoginIconAct
      break
    case 1:
      imgAddress[1].photo = passwordLoginIconAct
      break
    case 2:
      imgAddress[2].photo = phoneLoginIconAct
      break
    case 3:
      imgAddress[3].photo = simCardLoginIconAct
      break
  }
}