首页 > 解决方案 > 使用拼接设置数据后道具发生变化

问题描述

所以我得到了道具数据,就像这样:

props: {
  array: {
    type: Array,
    required: true,
  },
},

而且我必须声明 2 个数组第一个 - 标记之后的实际一个,第二个 - 之前在标记之前。

所以......要做到这一点,我做了类似的事情,内部方法:

checkExist() {
  const newArray = []
  const arr = this.array[this.counter].splice(1)
  arr.map(el => {
    !newArray.includes(el) ? newArray.push(el) : false
  })
  return newArray
},

所以现在我array[x]没有第一个项目,它就像一个魅力:D

但是...如果计数器大于 0,我将不得不添加一些额外的检查,所以我需要在映射之前知道数组内部的内容。

this.beforeSelect = this.array[this.counter - 1];

从数组返回索引为 0 的第一项,因为实际数组使用 splice(1)。第一项是标题。

那么,现在,如何进入正题?

我应该改变吗?

const arr = this.array[this.counter].splice(1);

但为了什么?

没有.splice(1),一切都很完美......但我需要splice。任何想法?

标签: vue.js

解决方案


首先,使用 splice 实际上会改变您作为道具传递的原始数组。你永远不想改变孩子的道具。如果您想更改作为道具传递的原始数组,这应该发生在父组件中。

如果您想创建该数组的本地副本,您可以使用

const arr = this.array[this.counter].slice()

这将创建一个本地副本,您可以根据自己的喜好进行修改,而无需更改原始副本。然后您可以通过拼接本地副本继续删除第一个索引。


推荐阅读