Skip to content

fix: handle v-for + custom directive should trigger unmounted #12572

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/runtime-core/src/directives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ return withDirectives(h(comp), [
])
*/

import type { VNode } from './vnode'
import { type VNode, currentBlock } from './vnode'
import { EMPTY_OBJ, isBuiltInDirective, isFunction } from '@vue/shared'
import { warn } from './warning'
import {
Expand Down Expand Up @@ -143,6 +143,9 @@ export function withDirectives<T extends VNode>(
for (let i = 0; i < directives.length; i++) {
let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i]
if (dir) {
if (currentBlock && !currentBlock.find(i => i === vnode)) {
currentBlock.push(vnode)
}
if (isFunction(dir)) {
dir = {
mounted: dir,
Expand Down
32 changes: 32 additions & 0 deletions packages/vue/__tests__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,38 @@ describe('compiler + runtime integration', () => {
expect(container.innerHTML).toBe(`<div>false<div>true</div></div>`)
})

test('should trigger custom directive unmounted hook with v-for', async () => {
const mounted = vi.fn()
const unmounted = vi.fn()
const visible = ref(true)
const App = {
directives: {
foo: {
mounted,
unmounted,
},
},
setup() {
const arr = [1, 2, 3]
return {
arr,
visible,
}
},
template: `<template v-if="visible">
<h1 v-for="i in arr" :key="i" v-foo></h1>
</template>`,
}

const container = document.createElement('div')
createApp(App).mount(container)
await nextTick()
expect(mounted).toHaveBeenCalledTimes(3)
visible.value = false
await nextTick()
expect(unmounted).toHaveBeenCalledTimes(3)
})

test('v-for + v-once', async () => {
const list = reactive([1])
const App = {
Expand Down
Loading