mirror of
https://github.com/robonen/tools.git
synced 2026-03-20 02:44:45 +00:00
feat(packages/vue): add useMounted composable
This commit is contained in:
27
packages/vue/src/composables/useMounted/index.test.ts
Normal file
27
packages/vue/src/composables/useMounted/index.test.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { defineComponent, nextTick, ref } from 'vue';
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { useMounted } from '.';
|
||||
|
||||
const ComponentStub = defineComponent({
|
||||
setup() {
|
||||
const isMounted = useMounted();
|
||||
|
||||
return { isMounted };
|
||||
},
|
||||
template: `<div>{{ isMounted }}</div>`,
|
||||
});
|
||||
|
||||
describe('useMounted', () => {
|
||||
it('return the mounted state of the component', async () => {
|
||||
const component = mount(ComponentStub);
|
||||
|
||||
// Initial render
|
||||
expect(component.text()).toBe('false');
|
||||
|
||||
await nextTick();
|
||||
|
||||
// Will trigger a render
|
||||
expect(component.text()).toBe('true');
|
||||
});
|
||||
});
|
||||
25
packages/vue/src/composables/useMounted/index.ts
Normal file
25
packages/vue/src/composables/useMounted/index.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { onMounted, readonly, ref, type ComponentInternalInstance } from 'vue';
|
||||
import { getLifeCycleTarger } from '../../utils';
|
||||
|
||||
/**
|
||||
* @name useMounted
|
||||
* @category Components
|
||||
* @description Returns a ref that tracks the mounted state of the component (doesn't track the unmounted state)
|
||||
*
|
||||
* @param {ComponentInternalInstance} [instance] The component instance to track the mounted state for
|
||||
* @returns {Readonly<Ref<boolean>>} The mounted state of the component
|
||||
*
|
||||
* @example
|
||||
* const isMounted = useMounted();
|
||||
*
|
||||
* @example
|
||||
* const isMounted = useMounted(getCurrentInstance());
|
||||
*/
|
||||
export function useMounted(instance?: ComponentInternalInstance) {
|
||||
const isMounted = ref(false);
|
||||
const targetInstance = getLifeCycleTarger(instance);
|
||||
|
||||
onMounted(() => isMounted.value = true, targetInstance);
|
||||
|
||||
return readonly(isMounted);
|
||||
}
|
||||
Reference in New Issue
Block a user