Today, when I was studying another problem of Xueyou (https://codeshelper.com/q/10.), I found a problem, that is, the use of computed.
first of all, the same paragraph declares VUE with the following code:
var valPlus = new Vue({
el: ".valPlus",
data: {
data_level_1: {
name: "1",
level: 1,
value: null,
children: this.data_arr_1
},
data_arr_1: [
{
name: "1-1",
level: 2,
value: null,
children: this.data_arr_2_1
},
{
name: "1-2",
level: 2,
value: null,
children: this.data_arr_2_2
}
],
data_arr_2_1: [
{
name: "1-1-1",
level: 3,
value: 12,
},
{
name: "1-1-1",
level: 3,
value: 24
}
],
data_arr_2_2: [
{
name: "1-2-1",
level: 3,
value: 122,
},
{
name: "1-2-2",
level: 3,
value: 242
}
]
},
computed: {
data_level_3_val_1: function (){
var res = 0
for (var i = 0; i < this.data_arr_2_1.length; iPP) {
res = res + this.data_arr_2_1[i].value
}
this.data_arr_1[0].value = res
return res
},
data_level_3_val_2: function (){
var res = 0
for (var i = 0; i < this.data_arr_2_2.length; iPP) {
res = res + this.data_arr_2_2[i].value
}
this.data_arr_1[1].value = res
return res
},
data_level_2_val: function (){
var res = 0
for (var i = 0; i < this.data_arr_1.length; iPP) {
res = res + this.data_arr_1[i].value
}
this.data_level_1.value = res
return res
}
}
})
<div class="valPlus">
data_arr_1[0].value:{{data_arr_1[0].value}}
data_level_3_val_1:{{data_level_3_val_1}}
data_arr_1[1].value:{{data_arr_1[1].value}}
data_level_3_val_2:{{data_level_3_val_2}}
</div>
the effect of the above code is
data_arr_1[0].value:36
data_level_3_val_1:36
data_arr_1[1].value:364
data_level_3_val_2:364
while commenting out the result of computed calculation:
<div class="valPlus">
data_arr_1[0].value:{{data_arr_1[0].value}}
<!-- data_level_3_val_1:{{data_level_3_val_1}}
-->
data_arr_1[1].value:{{data_arr_1[1].value}}
<!-- data_level_3_val_2:{{data_level_3_val_2}}
-->
</div>
display effect:
data_arr_1[0].value:
data_arr_1[1].value:
you can see that when the page is bound with the calculated value of computed, the data in data is also displayed; when the page is not bound to the calculated value of computed, the data in data is gone.
the personal conclusion is that computed, as an operation on the data in data, requires the data binding of the page to execute the corresponding function. Computed will not work if it is not bound.
is not clear about the operation principle of vue, let alone whether the above conclusion is correct, please give me some advice.
what should I do if I want to use computed to computationally bind data in data?