gpt4 book ai didi

javascript - 如何在Vuejs中使用数组在父组件和子组件之间应用监视

转载 作者:行者123 更新时间:2023-12-02 22:50:50 25 4
gpt4 key购买 nike

我制作了如下所示的父组件。

// parent component

<template>
<layout
v-for="(value, idx) in array"
:pickUpLength="array.length"
:idx="idx"
:key="idx"
>
<button @click="addArray">add</add>
</template>

data(){
array:[
{"date" : "", "time": ""},
{"date" : "", "time": ""}
]
}
methods:{
addArray(){
this.array.splice(this.array.length - 1, 0, {"yes":"no"})
}

还有一个子组件。

<template>

</template>

props:["pickUpLength"],
watch:{
pickUpLength:{
handler(){
console.log(idx)
}
}
}

当我单击父组件中的 addArray 按钮时,子组件的 pickUpLength 也会更改。
因此, watch 有效。但问题是 console.log(idx) 只给出“0, 1”。但在这种情况下,总 idx 是“3”而不是 2。
所以我期望“0,1,2”。我不知道问题出在哪。你能推荐一些解决方案吗?非常感谢您阅读它。

最佳答案

<template>
<layout
v-for="(value, idx) in array"
:pickUpLength="array.length"
:idx="idx"
:key="idx"
>
<button @click="addArray">add</add>
</template>

<script>
export default {
data() {
array:[
{"date" : "", "time": ""},
{"date" : "", "time": ""}
]
},
methods:{
addArray(newVal){
// This is what you are doing. You can't "watch" arrays or Objects in Vue.js v2.x.x (changing in v3.x.x).
// this.array.splice(this.array.length - 1, 0, {"yes":"no"})

// This is what you have to do in this situation (based upon your comments from my original answer):
this.array = this.array.slice(0, this.array.length - 1).concat(newVal, this.array[this.array.length - 1]);
}
}
};
</script>

关于javascript - 如何在Vuejs中使用数组在父组件和子组件之间应用监视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58185505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com