【发布时间】:2021-09-26 06:15:47
【问题描述】:
我在我的项目中使用vue 和firebase。所以最初,我以嵌套数组(数组中的数组)的形式将一些数据发送到后端。然后 firebase/firestore 开始大喊:
Function DocumentReference.set() called with invalid data. Nested arrays are not supported.
在网上搜索解决方案后,找到this answer
所以我在 vue 中初始化了我想要发送到后端的数据,如下所示,paths 数组将存储多个数组:
data() {
return {
product: {
images: [{paths: []}]
}
}
}
并将其保存到后端
this.product.images[0].paths.push([this.bigImgPath, this.thumbImgPath] // i.e push an array with 2 strings into the paths-array
它给我一个错误:
TypeError: Cannot read property 'paths' of undefined
这个answer很好地解释了这个问题,但我仍然得到错误,即使我通过this.product.images[0]引用了数组的第一个元素,它将paths作为键存储一个对象empty array 作为 value,然后使用 dot notation 访问该键的值(空数组)并推送我的新数组。如何成功地将带有两个字符串 (bigImgPath, thumbImgPath) 的数组添加到我的嵌套数据结构中?谢谢!
编辑:可重现的代码
new Vue({
el: "#app",
data: {
product: {
images: [{paths: []}]
},
bigImgPath : "/path/src/big.jpg",
thumbImgPath : "/path/src/thumb.jpg"
},
methods: {
myFunc: function(todo){
this.product.images[0].paths.push([this.bigImgPath, this.thumbImgPath])
console.log(this.product.images[0].paths[0][0])
console.log(this.product.images[0].paths[0][1])
document.getElementById("first-text").innerHTML = this.product.images[0].paths[0][0]
document.getElementById("second-text").innerHTML = this.product.images[0].paths[0][1]
}
}
})
.first-text {
font-size: 18px;
font-weight: bold;
}
.second-text {
font-size: 18px;
font-weight: bold;
}
.main-btn {
padding: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<html>
<body>
<div id="app">
<div id="main">
<p id="first-text"></p>
<p id="second-text"></p>
<button @click="myFunc()" class="main-btn">Press me!</button>
</div>
</div>
</body>
</html>
【问题讨论】:
-
你能用 jsfiddle 或 codepen 做一个可重现的例子吗?这看起来应该可以工作。
-
@Psidom 我已经添加了一些代码sn-p,看来我的语法很好。但是错误是未定义的,我猜这与 vue 的生命周期挂钩有关。因此,当我的函数触发时,该数据仍然不可用
-
该示例没有使用 Vue。您需要创建一个 Vue 示例来显示您当前遇到的问题。
-
@Psidom 我已经尝试过使用 Vue,但不知道为什么它在这里工作而不是在我的项目中。一切都和我的开发代码几乎一样
标签: javascript vue.js multidimensional-array data-manipulation