Aqu*_*guy 2 vue.js vue-component vuejs2 v-for
我有以下模板,我想在 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>
Run Code Online (Sandbox Code Playgroud)
该<row>元素是一个 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()
}
}
},
...
Run Code Online (Sandbox Code Playgroud)
小智 5
在每个组件上动态创建一个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>
Run Code Online (Sandbox Code Playgroud)
要在组件上调用方法,请执行以下操作:
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()
}
}
},
Run Code Online (Sandbox Code Playgroud)
$refs此处属性的更多信息:'ref' 属性的真正目的是什么?
| 归档时间: |
|
| 查看次数: |
2316 次 |
| 最近记录: |