CBWIRE
v4.x
v4.x
  • Introduction
  • How It Works
  • Getting Started
  • Configuration
  • Releases
    • What's New With 4.1
    • What's New With 4.0
    • What's New With 3.2
    • What's New With 3.1
    • What's New With 3.0
    • What's New With 2.2
    • What's New With 2.1
    • What's New With 2.0
  • Resources
  • Upgrading from CBWIRE 3.x
  • Upgrading from CBWIRE 2.x
  • CBWIRE CLI
  • The Essentials
    • Components
    • Templates
    • Data Properties
    • Computed Properties
    • Data Binding
    • Actions
    • Events
    • Nesting Components
    • Lifecycle Methods
    • JavaScript
    • Testing
  • Features
    • Single-file Components
    • Alpine.js
    • Lazy Loading
    • Form Validation
    • File Uploads
    • Query String
    • Redirecting
    • WireBox
  • Template Directives
    • wire:click
    • wire:confirm
    • wire:dirty
    • wire:ignore
    • wire:init
    • wire:key
    • wire:loading
    • wire:model
    • wire:navigate
    • wire:offline
    • wire:poll
    • wire:stream
    • wire:submit
    • wire:transition
  • Advanced
    • Troubleshooting
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Template Directives

wire:key

Overview

Using wire:key is essential, especially when looping over elements, to ensure that Livewire's DOM diffing correctly identifies what has changed and needs updating in the browser.

Consider this listing of posts.

// ./wires/Posts.cfc
component extends="cbwire.models.Component" {
    function posts() {
        return queryExecute( "select id,title from posts" );
    }
    function remove( postId ) {
        queryExecute( "delete from posts where id = :id", { id = postId } );
    }
}
<!--- ./wires/posts.cfm --->
<div>
    <cfloop array="#posts()#" index="post">
        <div>
            <h2>#post.title#</h2>
            <button wire:click="remove( #post.id# )">Remove</button>
        </div>
    </cfloop>
</div>

As posts are removed, CBWIRE re-renders our template, and then Livewire must figure out how to update the DOM. We can help Livewire know exactly what has changed using wire:key.

<div wire:key="post-#post.id#">
    <h2>#post.title</h2>
    ....
</div>
<!--- ./wires/posts.cfm --->
<div>
    <cfloop array="#posts()#" index="post">
        <div wire:key="post-#post.id#">
            <h2>#post.title#</h2>
            <button wire:click="remove( #post.id# )">Remove</button>
        </div>
    </cfloop>
</div>

It's important to ensure your key names are unique throughout the page, not just within your template. Otherwise, you may encounter weird rendering issues.

Previouswire:initNextwire:loading

Last updated 7 months ago

Was this helpful?