gpt4 book ai didi

vue.js - 访问通过 v-for 从对象数组创建的 vue 组件

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

我有以下模板,我想在 v-for 语句中调用动态创建的组件的方法。

例如,我想在每一行调用 row.getSubtotal()方法。我不知道该怎么做 this.rows返回原始数组而不是组件数组。

 <template>
<div>
<table class="table table-bordered">
<thead>
<th v-for="c in columns" v-bind:class="[c.className ? c.className : '']" :key="c.code">{{c.label}}</th>
</thead>
<tbody>
<row v-for="(row, index) in rows"
:index="index+1"
:init-data="row"
:columns="columns"
:key="row.hash"
:hash="row.hash"
v-on:remove="removeRow(index)"></row>
</tbody>
</table>
<div class="d-flex">
<table>
<tr>
<td>Unique SKUs:</td>
<td>{{rows.length}}</td>
<td>Total units:</td>
<td>{{totalUnits}}</td>
</tr>
</table>
<span class="flex-fill"></span>
<button class="btn" @click="newRow">Nueva línea</button>
</div>
</div>
</template>

<row> element 是一个 Vue 组件,它是通过 rows 属性创建的,其中包含具有每个 rows 属性的对象数组。例如:

...
import Row from './Row'

export default {
name: "OrderTable",
components: {Row},
data: () => ({
hashes: [],
rows: [
{hash: '_yug7', sku: '85945', name: 'Coconut butter', price: 20},
{hash: '_g484h', sku: '85745', name: 'Coconut oil', price: 15},
{hash: '_yug7', sku: '85945', name: 'Cramberry juice', price: 5},
],
fixedColumns: [
{code: 'index', label: '#'},
{code: 'sku', label: 'SKU'},
{code: 'name', label: 'Product name', className: 'text-left align-middle'},
{code: 'quantity', label: 'Units'},
{code: 'price', label: 'Price', className: 'text-right align-middle'}
]
}),
computed: {
totalUnits: function () {
for(let x in this.rows) {
// HERE I WANT TO CALL A METHOD IN THE ROW COMPONENT
// For example this.rows[x].getSubtotal()
}
}
},
...

最佳答案

动态创建ref每个组件上的属性并随后调用它:

<template>
<div>
<table class="table table-bordered">
<thead>
<th v-for="c in columns" v-bind:class="[c.className ? c.className : '']" :key="c.code">{{c.label}}</th>
</thead>
<tbody>

<!-- Add the ref attribute to each row -->
<row v-for="(row, index) in rows"
:ref="`myRow${index}`"
:index="index+1"
:init-data="row"
:columns="columns"
:key="row.hash"
:hash="row.hash"
v-on:remove="removeRow(index)"></row>

</tbody>
</table>
<div class="d-flex">
<table>
<tr>
<td>Unique SKUs:</td>
<td>{{rows.length}}</td>
<td>Total units:</td>
<td>{{totalUnits}}</td>
</tr>
</table>
<span class="flex-fill"></span>
<button class="btn" @click="newRow">Nueva línea</button>
</div>
</div>
</template>

要调用组件上的方法,请执行以下操作:

computed: {
totalUnits: function () {
for(let (x, index) in this.rows) {
let row = this.$refs[`myRow${index}`]
// You now have an instance of the component
let subtotal = row.getSubtotal()
}
}
},

有关 $refs 属性的更多信息:what's the real purpose of 'ref' attribute?

关于vue.js - 访问通过 v-for 从对象数组创建的 vue 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51480954/

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