Skip to content

Commit f37c5a1

Browse files
committed
Handle member expressions in v-for statements
We currently support iterating over arrays in Vue statements, like `<a v-for="item in list">`, but this support is currently limited to data at the top-level of our template data object. Add support for member expressions in v-for statements so that we can handle statements like `<a v-for="item in list.data">`. Bug: T398011
1 parent 2ed9ddd commit f37c5a1

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

src/Component.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
use DOMNodeList;
1010
use DOMText;
1111

12+
use WMDE\VueJsTemplating\JsParsing\VariableAccess;
13+
1214
class Component {
1315

1416
/**
@@ -204,8 +206,10 @@ private function handleFor( DOMNode $node, array $data ) {
204206
if ( $node->hasAttribute( 'v-for' ) ) {
205207
list( $itemName, $listName ) = explode( ' in ', $node->getAttribute( 'v-for' ) );
206208
$node->removeAttribute( 'v-for' );
209+
$node->removeAttribute( ':key' );
210+
$listNameExpression = new VariableAccess( explode( '.', $listName ) );
207211

208-
foreach ( $data[$listName] as $item ) {
212+
foreach ( $listNameExpression->evaluate( $data ) as $item ) {
209213
$newNode = $node->cloneNode( true );
210214
$node->parentNode->insertBefore( $newNode, $node );
211215
$this->handleNode( $newNode, array_merge( $data, [ $itemName => $item ] ) );

tests/php/TemplatingTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,15 @@ public function testTemplateWithForLoopAndSingleElementInArrayToIterate_Rendered
207207
$this->assertSame( '<p><a></a></p>', $result );
208208
}
209209

210+
public function testTemplateWithForLoopAndMemberExpressionForData_RenderedOnce() {
211+
$result = $this->createAndRender(
212+
'<p><a v-for="item in list.data"></a></p>',
213+
[ 'list' => [ 'data' => [ 1 ] ] ]
214+
);
215+
216+
$this->assertSame( '<p><a></a></p>', $result );
217+
}
218+
210219
public function testTemplateWithForLoopAndMultipleElementsInArrayToIterate_RenderedMultipleTimes() {
211220
$result = $this->createAndRender(
212221
'<p><a v-for="item in list"></a></p>',

0 commit comments

Comments
 (0)