Ben Lin
2025-03-08 7f5b781c9b476eb1c74dd637cbf9ee54bc71acfd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import type { CSSProperties, DirectiveBinding, ObjectDirective, App } from 'vue';
 
interface IValue {
  width?: number;
  line?: number;
}
 
interface IOptions {
  [key: string]: CSSProperties;
}
 
const cssProperties: IOptions = {
  single: {
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
  },
  multiple: {
    display: '-webkit-box',
    overflow: 'hidden',
    wordBreak: 'break-all',
  },
};
 
const Ellipsis: ObjectDirective = {
  mounted(el: HTMLElement, binding: DirectiveBinding<Array<IValue>>) {
    const { value = [100, 1], arg = 'single' } = binding;
    const [width, line] = value;
    Object.entries(cssProperties[arg]).forEach(([key, value]) => {
      el.style[key] = value;
    });
    el.style.width = `${width}px`;
    if (arg === 'multiple') {
      el.style.webkitLineClamp = `${line}`;
      el.style.webkitBoxOrient = 'vertical';
    }
  },
};
export function setupEllipsisDirective(app: App) {
  app.directive('ellipsis', Ellipsis);
}
export default Ellipsis;