vue3+ts api 代码结构

本文介绍了在Vue3中结合Vite和TypeScript使用API和组件的方法,包括ref和reactive声明响应式变量,定义Props类型,计算属性的创建和类型标注,以及监听器的使用。同时,详细讲解了父子组件间通信的emit功能,并提到了Vue3中的新特性如setup语法糖。

vue3 + vite + ts 使用api及组件,ts与组合api:
通过setup 语法糖: <script lang="ts" setup name="AddPage"> 业务 </script>


业务:
1、ref  reactive 变量声明:

import { ref, reactive  } from 'vue'

import type { Ref } from 'vue'


// 使用: obj.value.type 取值与赋值(通过.value) 基础类型推导
const obj = ref({
     type: "checkbox",
    showCheckedAll: true,
    onlyCurrent: false
 })

 // 使用: rowSelection.type  直接取值   
 const rowSelection = reactive({
    type: "checkbox",
    showCheckedAll: true,
    onlyCurrent: false
});


2 标注类型
const year: Ref<string | number> = ref('2020')

2.1 传入一个泛型参数,来覆盖默认的推导行为:
// 得到的类型:Ref<string | number>
const year = ref<string | number>('2020')


3 reactive 通过接口标注类型

interface Book {
  title: string
  year?: number
}

const book: Book = reactive({ title: 'Vue 3的 指引' })

2、父子传参 defineProps ,  通过withDefaults配置默认值:

a、defineProps() 宏函数支持从它的参数中推导类型:

b、 “运行时声明”,因为传递给 defineProps() 的参数会作为运行时的 props 选项使用。

// 标准类型

const props = defineProps({
  foo: { type: String, required: true },
  bar: Number
})

//  “运行时声明”
//2.1 无默认值:
const props1 = defineProps<{
        name: string;
        isActive: boolean;
        rightDisable: boolean;
        tabStyleType: number;
        modelValue: { key: number; title: string; subTitle: string };
    }>();
// 2.2 通过 withDefaults编译器设置默认值: 解构默认值
const props2 = withDefaults(
    defineProps<{
        name: string;
        isActive: boolean;
        rightDisable: boolean;
        tabStyleType: number;
        modelValue: { key: number; title: string; subTitle: string };
    }>(),
    {
        isActive: false,
        rightDisable: false,
        tabStyleType: 1
    }
);


3 通过单接口定义:将 props 的类型移入一个单独的接口中
interface Props {
  foo: string
  bar?: number
}

const props = defineProps<Props>()



3、计算属性

// 3.1 取值:
  const rightTabs = computed(() => {
       return [{ label: "页面设置", value: 1 }];
  });
// 3.2 双向:
const previewArr = computed({
    get: () => {
        return obj;
    },
    set: (newVal) => {
        updata(newVal);
    }
});


标注类型:
const double = computed<number>(() => {
  // 若返回值不是 number 类型则会报错
  return  333 * 20;
})

4、监听器 watch

4.1 基础

watch(sortType, () => {
    getData();
});


4.2 深度
watch(
    (): any => route?.query?.tab, // 1 source: WatchSource<any> 监听的数据源
    () => {       // 2 cb: WatchCallback 监听回调
        const tab = route?.query?.tab;
        if (tab) {
            active.value = tab as Tlabel;
            previewActive.value = tab as Tlabel;
        }
    },
    { deep: true, immediate: true } // 3、options?: WatchOptions 配置
);


5、子组件通信与父组件  emit



5.1  方法一: 标注类型
const emits = defineEmits<{
    (e: "update:modelValue", data: any): void;
    (e: "rightClick"): void;
}>();
5.2  方法二:运行时
const emits = defineEmits(["update:modelValue", "rightClick"]);

使用 emits("update:modelValue", newVal);
     emits("rightClick", newVal);

二、小拓展:

(1)、vue3 常用的操作符号:

1、 ??  :    numObj ??  "报错结果值"

2、链式操作符 ''  ?.  "  具有短路功能:   obj?.data?.name

(2)插件: 1、状态 pinia    2、处理事件  dush  .....

--------------------------笔记1结束---------------------------

### 代码模块化组织的核心思路 在 Vue3TypeScript 的结合环境下,代码的模块化组织主要依赖于 TypeScript 的模块化能力以及 Vue3 的组件化设计。通过合理的文件结构和模块划分,可以显著提升项目的可维护性和可扩展性。 #### 1. 使用 TypeScript 的模块化机制 TypeScript 支持通过 `import` 和 `export` 语句实现模块化,这使得代码可以被拆分成多个独立的文件或模块,每个模块专注于单一职责。例如,在数据请求模块中,可以定义一个泛型函数来处理不同类型的 API 响应: ```typescript // src/hooks/useURLLoader.ts import { ref } from &#39;vue&#39;; function useURLLoader<T>(url: string) { const result = ref<T | null>(null); const loading = ref(true); const loaded = ref(false); fetch(url) .then((res) => res.json()) .then((data) => { result.value = data; loading.value = false; loaded.value = true; }) .catch((err) => { console.error(err); loading.value = false; }); return { result, loading, loaded }; } export default useURLLoader; ``` 通过这种方式,可以在应用的不同部分复用该函数,并根据具体需求指定不同的数据类型[^3]。 #### 2. Vue3 的组件化与模块化 Vue3 的组件化设计天然支持模块化开发。每个组件可以包含自己的模板、逻辑和样式,独立于其他组件。例如,一个弹窗组件可以封装其内部状态和行为,仅通过 `props` 暴露必要的接口: ```vue <template> <div class="modal"> <div class="modal-header"> <h3>{{ title }}</h3> </div> <div class="modal-body"> <slot></slot> </div> <div class="modal-footer"> <button @click="onClose">关闭</button> <button @click="onSubmit">提交</button> </div> </div> </template> <script setup lang="ts"> defineProps<{ title: string; }>(); const emit = defineEmits<{ (e: &#39;close&#39;): void; (e: &#39;submit&#39;): void; }>(); const onClose = () => { emit(&#39;close&#39;); }; const onSubmit = () => { emit(&#39;submit&#39;); }; </script> <style scoped> .modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 600px; max-height: 80vh; overflow: hidden; display: flex; flex-direction: column; border: 1px solid #ccc; background: #fff; } .modal-header { padding: 16px; border-bottom: 1px solid #e4e7ed; } .modal-body { flex: 1; overflow-y: auto; padding: 16px; } .modal-footer { padding: 12px 16px; background-color: #f5f7fa; border-top: 1px solid #e4e7ed; display: flex; justify-content: flex-end; gap: 10px; } </style> ``` 通过组件化设计,可以将复杂的 UI 拆解为多个可维护的小模块,提升开发效率[^2]。 #### 3. 路由模块化组织 在 Vue3 中,结合 `vue-router` 可以实现路由的模块化组织。通过将路由配置拆分为多个模块,可以更好地管理不同功能区域的路由逻辑: ```typescript // src/router/modules/home.ts import { RouteRecordRaw } from &#39;vue-router&#39;; const homeRoutes: RouteRecordRaw[] = [ { path: &#39;/&#39;, name: &#39;Home&#39;, component: () => import(&#39;@/views/Home.vue&#39;), meta: { outMenu: true, }, }, ]; export default homeRoutes; ``` 在主路由文件中,可以自动化导入所有路由模块: ```typescript // src/router/index.ts import { createRouter, createWebHistory, RouteRecordRaw } from &#39;vue-router&#39;; const modulesRoutes: RouteRecordRaw[] = []; const modulesFiles = require.context(&#39;./modules&#39;, false, /\.ts$/); modulesFiles.keys().forEach((modulePath: string) => { const module = modulesFiles(modulePath).default; if (module) { modulesRoutes.push(...module); } }); const routes: RouteRecordRaw[] = [ ...modulesRoutes, { path: &#39;*&#39;, component: () => import(&#39;@/views/404.vue&#39;), meta: { notLogin: true, }, }, ]; const router = createRouter({ history: createWebHistory(), routes, }); export default router; ``` 这种模块化方式不仅提升了代码的可读性,还便于团队协作和功能扩展[^4]。 #### 4. 状态管理模块化 在 Vue3 中,结合 `Pinia` 可以实现状态管理的模块化。通过将不同的状态逻辑拆分为多个 store 模块,可以更清晰地管理应用的状态: ```typescript // src/stores/userStore.ts import { defineStore } from &#39;pinia&#39;; interface User { id: number; name: string; } export const useUserStore = defineStore(&#39;user&#39;, { state: (): { user: User | null } => ({ user: null, }), actions: { setUser(newUser: User) { this.user = newUser; }, }, }); ``` 在组件中使用该 store: ```vue <script setup lang="ts"> import { useUserStore } from &#39;@/stores/userStore&#39;; const userStore = useUserStore(); </script> ``` 通过模块化状态管理,可以避免全局状态的混乱,提升应用的可测试性和可维护性。 --- ### 相关问题 1. 如何在 Vue3 中实现组件之间的通信? 2. 如何在 Vue3 中使用 TypeScript 定义接口和类型? 3. 如何在 Vue3 中配置 ESLint 和 Prettier 以提升代码质量? 4. 如何在 Vue3 中实现动态路由加载? 5. 如何在 Vue3 中使用 Pinia 进行状态管理?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值