gpt4 book ai didi

vue.js - 从组件计算值创建根计算值?

转载 作者:搜寻专家 更新时间:2023-10-30 22:49:28 24 4
gpt4 key购买 nike

我对 Vue 有点陌生,我正在尝试弄清楚如何从组件的计算值访问计算值。请查看此 fiddle :https://jsfiddle.net/85ma3rct/

 <script src="https://unpkg.com/vue"></script>
<div id="app">
<table>
<floor></floor>
<floor></floor>
<floor></floor>
</table>
Largest area: {{ largest_area}}
</div>

Vue.component('floor', {
data: function () {
return {
width: 20,
height: 20
}
},
computed: {
area: function () {
return this.width * this.height;
}
},
template: '<tr><td><input type="number" v-model="width"></td>' +
'<td><input type="number" v-model="height"></td>' +
'<td>{{ area }}</td>' +
'</tr>'
})

new Vue({
el: '#app',
computed: {
largest_area: function () {
// How to get this from component computed values...
return 0
}
},
})

如何通过多个分量中的计算值得到最大面积的计算值?

最佳答案

一种可能的解决方案是观察子组件中区域值的变化并向父组件发出值

  watch: {
area: {
handler() {
this.$emit('input', this.area)
},
immediate: true
}
},

然后在父级

<table>

<floor @input="changeVal($event, 0)"></floor>
<floor @input="changeVal($event, 1)"></floor>
<floor @input="changeVal($event, 2)"></floor>

</table>

new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
areas: [0, 0, 0]
},
computed: {
largest_area: function () {
return Math.max(...this.areas)
}
},
methods: {
changeVal(val, index) {
this.$set(this.areas, index, val)
}
}
})

此处演示 https://jsfiddle.net/ittus/kuo9crjm/1/

关于vue.js - 从组件计算值创建根计算值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57174472/

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