WeShare
admin đăng 3 năm trước (cập nhật 3 năm trước)

Binding prop trong Vue Typescript

Xin chào mọi người Mình đang học vue và đang làm project cơ bản để học nó Mình dùng vue 3 và typescript Mình đang có một component MenuItem có type cơ bản như sau

interface MenuItemProps {
  title: string;
  to?: string | '';
  icon?: IconName | '';
}
withDefaults(defineProps<MenuItemProps>(), {
  to: '',
  icon: '',
});

1 prop required và 2 prop optional => Ở đây mình muốn vừa là link vừa là item normal cho các action như show modal và change language.

Ở component Menu mình gọi nó như sau

export const BASE_MENU: BaseMenu[] = [
  {
    icon: 'language',
    title: 'Language',
    languages: languages.map((lang) => ({
      title: lang.title,
      lang: lang.lang,
    })),
  },
  {
    icon: 'help',
    title: 'Help',
  },
];

interface MenuItem {
  title: string;
  icon: IconName;
}

export interface MenuItemLink extends MenuItem {
  to: string;
}

export interface MenuItemLangue extends Omit<MenuItem, 'icon'> {
  languages?: {
    title: string;
    lang: string;
  }[];
}

export type BaseMenu = MenuItemLangue & Partial<Pick<MenuItemLink, 'to' | 'icon'>>;

type Menu = BaseMenu[] | MenuItemLangue;

const menuItems = reactive<{ data: Menu }>({ data: props.items });

const handleChange = (item: BaseMenu, _evt: Event) => {
  if (item.icon === 'language') {
    menuItems.data = item;
  } 
  ...
};

...
 <MenuItem
              v-for="(item, index) in currentMenuList"
              :key="index"
              :to="item.to" 
             :icon="item.icon"
              @onClick="(event) => handleChange(item, event)"
/>

Ở đây mình muốn là là khi bấm vào cái menu item language thì render list languages.

Ở đây thì mỗi item trong currentMenuList nó sẽ có 2 type 

Lúc này mình passing :to="item.to" :icon="item.icon" thì typescript lỗi là Property 'icon' does not exist on type '{ title: string; lang: string; }' Lúc này mình search gg thử thì có thấy dùng v-bind. Mình lại thử như này thì vẫn lỗi v-bind="{ to: item?.to || '', icon: item?.icon || '', title: item.title }"

Mình lại tiếp tục thử kiểu này.

<MenuItem
              v-for="(item, index) in currentMenuList"
              :key="index"
              v-bind="item"
              @onClick="(event) => handleChange(item, event)"
            />

Vâng thế này thì nó hết lỗi. Nhưng có vẽ không hay lắm, khó biết được props mình passing.

Mọi người có cách nào binding mà không dính lỗi type không ạ?
 

2
5 câu trả lời
1
cirno 3 năm trước

afasf

0
cirno 3 năm trước

asffas

0
user 3 năm trước

saff

0
cirno 3 năm trước

0
comaybay 2 năm trước

asfnknlkansf