Vue.js递归组件的数据,包括 props



我在vue.js中使用递归组件。每个组件都有一个数组,其中一个值作为prop从父组件传递过来。我如何创建数组正确包括值/道具?

下面是简化(未经测试)代码的细节,以显示理论问题(我知道这个例子会导致无限递归:-):

My-component.vue

<template>
{{my_array}}
<my-component :my_counter="my_array.counter">
</template>
<script>
module.exports = {
props: ['my_counter'],
name: 'my-component', 
data: function () {
return {
new_counter: this.my_counter+1,
my_array: [name: "static name", counter: this.new_counter]
}
},
}
</script>

虽然new_counter作为my_counter prop正确地传递给了子组件,但是my_array。计数器没有正确地更新为新值。

当我直接传递new_counter作为my_counter属性时(不使用数组)。它的工作原理。

我想我需要使用某种反应数据。然而,我找不到一个解决方案与计算属性,方法等…我怎么能使my_array更新通过的道具?

你有什么建议来解决这个问题?

您的代码的问题是,my_array初始化一旦使用道具,但然后它不更新。你必须像这样添加一个监视器:

watch: {
my_counter(value) {
this.my_array = {
...this.my_array,
counter: value
}
}
}

我对Vue.js很陌生,我对它和next .js有类似的问题。不过,我有一个例子可以帮助你。你试过这样的东西吗?

<template>
{{my_array}}
<my-component :my_counter="compA()">
</template>
<script>
module.exports = {
props: ['my_counter'],
name: 'my-component', 
computed: {
compA() {
const my_counter = this.my_counter ? this.my_counter : []; 
let my_array = [name: "static name", counter: my_counter];
return my_array;
}
}
}
</script>

最新更新