vue3中使用ts

ref方式指定自定义组件类型

import { ElForm } from 'element-plus'

// InstanceType是无需显示引入的
type FormInstance = InstanceType<typeof ElForm>
const elFormRef = ref<FormInstance>()

某种类型可以是自定义的多种类型

type RouteLocationRaw = string | (RouteQueryAndHash & LocationAsPath & RouteLocationOptions) | (RouteQueryAndHash & LocationAsRelativeRaw & RouteLocationOptions);

Composition API形式

<script setup lang="ts">
import { computed, toRefs } from 'vue'
import { Expand } from '@element-plus/icons-vue'
import { SystemMenuType } from '@/system'
import { SvgIcon } from 'components/index'
import { useRouter } from 'vue-router'

const props = withDefaults(
  defineProps<{
    /**
     * 是否启用侧边栏风格模式. 默认:true. 表示垂直菜单,否则表示水平菜单
     */
    enableSideModel?: boolean
    /**
     * 菜单是否收缩(只有enableSideModel为true时有效). 默认: false
     */
    menuCollapse?: boolean
    /**
     * 菜单数据. 默认:空数组
     */
    menuArr?: SystemMenuType[]
  }>(),
  { enableSideModel: true, menuCollapse: false, menuArr: () => [] }
)
/* eslint-disable */
const $emits = defineEmits({
  /**
   * 菜单展开/收缩事件
   * @param collapse
   */
  menuCollapse: (collapse: boolean) => true,
})
/* 
下面这种方式也是可以的,不过上面的方式,可以进行类型检查,
并且写起来更方便一边,不过要注意使用 eslint-disable 和 eslint-enable 
来去除eslint相关警告
*/
// const $emits = defineEmits<{
//   /**
//    * 菜单展开/收缩事件
//    * @param collapse true表示收缩, false表示展开
//    */
//   (e: 'menuCollapse', collapse: boolean): void
// }>()

/* eslint-enable */
const { enableSideModel, menuCollapse } = toRefs(props)
const enableJsMenuModelClass = computed(() =>
  enableSideModel.value ? 'jsSideMenuModel' : 'jsTopMenuModel'
)
const elMenuMode = computed(() =>
  enableSideModel.value ? 'vertical' : 'horizontal'
)

/**
 * 判断是否有子菜单
 * @param menuItem
 */
function hasChildrenMenu(menuItem: SystemMenuType) {
  return menuItem.children && menuItem.children.length > 0
}

function buildIndex(menuItem: SystemMenuType, idx?: number) {
  if (idx) {
    return `${menuItem.code}-${idx}`
  } else {
    return menuItem.code
  }
}

function buildMenuName(menuItem: SystemMenuType) {
  return menuItem.name
}

function onElMenuCollapse() {
  $emits('menuCollapse', !menuCollapse.value)
}

const $router = useRouter()

function onMenuItemClick(menuItem: SystemMenuType) {
  if (menuItem.url) {
    if (
      menuItem.url.startsWith('http://') ||
      menuItem.url.startsWith('https://')
    ) {
      window.open(menuItem.url)
    } else {
      $router.push({ path: menuItem.url })
    }
  }
}
</script>

<template>
  <div class="cSystemMenu" :class="enableJsMenuModelClass">
  </div>
</template>

<style lang="scss" scoped>
</style>

Options API

<template>
  <div>
    <h1>测试界面</h1>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue';

export interface ColumnProps {
  id: number;
  title: string;
  avatar: string;
  description: string;
}

export default defineComponent({
  name: 'ColumnList',
  props: {
    list: {
      type: Array as PropType<ColumnProps[]>,
      required: true,
    },
    success: { type: String },
    callback: {
      type: Function as PropType<() => void>
    },
  },
  setup() {
    return {};
  },
});
</script>

<style lang="less" scoped>
</style>

参考文章

Vue3 + TS 最佳实践

TypeScript高级特性

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3使用TypeScriptTS)定义数据的方法有几种。首先,你可以使用defineProps函数来定义组件的props。你可以通过传递一个泛型参数来指定props的类型。例如: ``` import { defineProps } from 'vue'; interface Props { id: number; arr: string[]; } const props = defineProps<Props>(); ``` 在这个例子,我们定义了一个Props接口来指定props的类型,并通过defineProps<Props>()函数来定义props。你可以在Props接口定义每个prop的类型,并在组件使用这些props。 另一种方法是使用ref函数来定义组件的引用实例。你可以通过在ref函数的泛型指定类型来获取组件的类型。例如: ``` import { ref } from 'vue'; import NewsDialog from './components/NewsDialog.vue'; const news = ref<InstanceType<typeof NewsDialog>>(); // 打开消息弹窗 const openNewsDialog = (): void => { news.value?.showDialog(); } ``` 在这个例子,我们使用ref函数来定义NewsDialog组件的引用实例,并使用InstanceType<typeof NewsDialog>来获取组件的类型。然后,我们可以使用news.value来访问组件的方法或属性。 还有一种方法是使用computed函数来定义计算属性。computed函数会自动推导出计算函数的返回值类型。例如: ``` import { ref, computed } from 'vue'; const count = ref(0); const double = computed(() => count.value * 2); const result = double.value.split(''); // 这里会报错,因为double的类型是number // 显式指定类型 const double = computed<number>(() => { // 若返回值不是number类型则会报错 }); ``` 在这个例子,我们使用computed函数定义了一个计算属性double,它返回count的值乘以2。computed函数会自动推导出double的类型为ComputedRef<number>。你也可以通过在computed函数的泛型参数显式指定类型。 最后,如果你想在Vue 3使用provide和inject来实现组件之间的数据传递,你可以使用InjectionKey来指定注入的值的类型。例如: ``` import { provide, inject } from 'vue'; import { InjectionKey } from 'vue'; const key = Symbol() as InjectionKey<string>; provide(key, 'foo'); const foo = inject(key); // foo的类型为string | undefined ``` 在这个例子,我们使用provide函数提供了一个key和一个值'foo'。然后,在另一个组件使用inject函数来获取这个值。你可以使用InjectionKey来指定注入值的类型,并在组件使用这个类型来声明变量。 这些是在Vue 3使用TypeScript定义数据的一些方法。你可以根据具体需求选择使用哪种方法来定义数据。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [vue3.0+TS使用](https://blog.csdn.net/yxlyttyxlytt/article/details/128057058)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值