ikVue
导入方式
import { ikVue } from 'iking-utils'
withInstall
用于为组件添加 install 方法,以便在 Vue 3 的应用中进行全局注册
vue
<script setup>
export const withInstall = <T>(component: T, alias?: string) => {
const comp = component as any;
comp.install = (app: any) => {
app.component(comp.name || comp.displayName, component);
if (alias) {
app.config.globalProperties[alias] = component;
}
};
return component as T & any;
};
</script>
示例
vue
<script setup>
// 定义一个示例组件
const MyComponent = {
name: 'MyComponent',
template: '<div>My Component</div>'
};
// 用' withInstall '函数包装组件
const MyComponentWithInstall = withInstall(MyComponent, 'myAlias');
</script>
getSlot
用于从给定的槽对象中检索特定的槽
vue
<script setup>
export function getSlot(slots: any, slot = 'default', data?: any) {
if (!slots || !Reflect.has(slots, slot)) {
return null;
}
if (!paramType.isFunction(slots[slot])) {
console.error(`${slot} is not a function!`);
return null;
}
const slotFn = slots[slot];
if (!slotFn) return null;
return slotFn(data);
}
</script>
示例
vue
<script setup>
const slotsData = {
default: () => {
console.log('Default slot called');
},
custom: (data: any) => {
console.log('Custom slot called with data:', data);
},
myComponent: (data: any) => {
return {
name: 'MyComponent',
template: `<div>${data?.name || 'My Components'}</div>`
}
}
};
const result2 = ikVue.getSlot(slotsData, 'custom', { foo: 'bar' }); // Custom slot called with data: {foo: 'bar'}
</script>
参数说明
参数值 | 类型 | 默认值 | 参数值说明 |
---|---|---|---|
slots | any | - | 包含不同槽位的对象。 |
slot | String | 'default' | 可选参数,要检索的槽的名称。 |
data | any | [] | 可选参数,可以传递给slot函数的附加数据 |
extendSlots
返回' ret '对象,它包含扩展槽。
vue
<script setup>
/**
* extends slots
* @param slots
* @param excludeKeys
*/
export function extendSlots(slots: any, excludeKeys: string[] = []) {
const slotKeys = Object.keys(slots);
const ret: any = {};
slotKeys.map((key) => {
if (excludeKeys.includes(key)) {
return null;
}
ret[key] = (data?: any) => getSlot(slots, key, data);
});
return ret;
}
</script>
参数说明
参数值 | 类型 | 默认值 | 参数值说明 |
---|---|---|---|
slots | any | - | 包含不同槽位的对象。 |
excludeKeys | string[] | [] | 可选参数,它是一个字符串数组。它用于指定应该从扩展槽中排除的键 |
示例
vue
<script setup>
const slotsData = {
default: () => {
console.log('Default slot called');
},
custom: (data: any) => {
console.log('Custom slot called with data:', data);
},
myComponent: (data: any) => {
return {
name: 'MyComponent',
template: `<div>${data?.name || 'My Components'}</div>`
}
}
};
// 扩展插槽对象并获取扩展后的插槽函数
const extendedSlots = ikVue.extendSlots(slots, ['custom']);
</script>