当前位置: 首页 > news >正文

vue3的ts页面初始化模板代码

vue3的ts页面初始化模板代码

在 Vue 3 中使用 TypeScript 开发时,主要有两种编写页面的方式。以下是两种风格的模板代码,你可以根据项目需求选择使用。

📝 两种页面初始化模板

1. 标准 Composition API 写法

这种写法使用defineComponent和明确的setup函数,结构清晰,适合初学者和需要明确控制暴露内容的情况。

<template><divclass="page-container"><h1>{{pageTitle}}</h1><p>计数器:{{count}}</p><button @click="increment">增加</button><button @click="reset">重置</button></div></template><script lang="ts">import{defineComponent,ref}from'vue';exportdefaultdefineComponent({name:'MyPage',setup(){// 响应式数据constpageTitle=ref<string>('Vue 3 + TypeScript 页面');constcount=ref<number>(0);// 方法constincrement=():void=>{count.value++;};constreset=():void=>{count.value=0;};// 生命周期钩子constinitialize=():void=>{console.log('页面初始化完成');};// 返回模板中需要使用的数据和方法return{pageTitle,count,increment,reset,initialize};},mounted(){this.initialize();}});</script><style scoped>.page-container{padding:20px;max-width:800px;margin:0auto;}</style>

2.<script setup>语法糖写法(推荐)

这种写法更简洁,不需要显式返回数据,适合 Vue 3.2+ 版本,是目前的主流写法。

<template><divclass="page-container"><h1>{{pageTitle}}</h1><p>计数器:{{count}}</p><p>双倍计数:{{doubleCount}}</p><button @click="increment">增加</button><button @click="reset">重置</button></div></template><script setup lang="ts">import{ref,computed,onMounted}from'vue';// 响应式数据constpageTitle=ref<string>('Vue 3 + TypeScript 页面');constcount=ref<number>(0);// 计算属性constdoubleCount=computed(():number=>count.value*2);// 方法constincrement=():void=>{count.value++;};constreset=():void=>{count.value=0;};// 生命周期钩子onMounted(():void=>{console.log('页面初始化完成');initialize();});constinitialize=():void=>{// 初始化逻辑console.log('初始化页面数据');};</script><style scoped>.page-container{padding:20px;max-width:800px;margin:0auto;}button{margin:05px;padding:8px16px;cursor:pointer;}</style>

🔧 高级功能扩展模板

如果需要更复杂的功能,可以参考以下包含路由、状态管理和API调用的完整模板:

<template><divclass="advanced-page"><header><h1>{{pageTitle}}</h1><nav><router-link to="/home">首页</router-link><router-link to="/about">关于</router-link></nav></header><main><div v-if="loading"class="loading">加载中...</div><div v-else><slot name="content"><p>用户数据:{{userData}}</p><button @click="fetchData":disabled="loading">{{loading?'加载中...':'获取数据'}}</button></slot></div></main></div></template><script setup lang="ts">import{ref,computed,onMounted}from'vue';import{useRouter}from'vue-router';// 类型定义interfaceUser{id:number;name:string;email:string;}interfacePageProps{title?:string;}// Props 定义constprops=withDefaults(defineProps<PageProps>(),{title:'默认页面标题'});// 响应式数据constpageTitle=ref<string>(props.title);constloading=ref<boolean>(false);constuserData=ref<User|null>(null);// 计算属性consthasUserData=computed(():boolean=>userData.value!==null);// 方法constfetchData=async():Promise<void>=>{loading.value=true;try{// 模拟 API 调用constresponse=awaitfetch('/api/user');userData.value=awaitresponse.json();}catch(error){console.error('获取数据失败:',error);}finally{loading.value=false;}};// 生命周期onMounted(async():Promise<void>=>{awaitfetchData();});// 暴露给父组件的方法defineExpose({fetchData,resetData:()=>{userData.value=null;}});</script><style scoped>.advanced-page{min-height:100vh;background-color:#f5f5f5;}header{background:#fff;padding:1rem;box-shadow:02px4pxrgba(0,0,0,0.1);}.loading{text-align:center;padding:2rem;color:#666;}button:disabled{opacity:0.6;cursor:not-allowed;}</style>

💡 关键要点说明

  1. 类型安全:TypeScript 提供了完整的类型支持,减少运行时错误 。
  2. 响应式系统:使用refreactive创建响应式数据 。
  3. 组合式函数:可以将逻辑抽离为可复用的组合式函数 。
  4. 生命周期:使用onMountedonUpdated等组合式 API 替代选项式 API 。

🎯 使用建议

  • 简单页面:推荐使用<script setup>语法糖,代码更简洁。
  • 复杂组件:如果需要明确的控制和组织结构,可以使用标准写法。
  • 团队项目:统一代码风格,制定 TypeScript 规范。
http://www.gsyq.cn/news/138341.html

相关文章:

  • LangFlow零废弃生活挑战助手设计
  • BioSIM抗人LOXL2抗体SIM0405:攻克肿瘤基质屏障
  • 0x3f第12天 0-1背包
  • LangFlow水族箱生态监控报警系统设想
  • LangFlow求职信个性化撰写助手
  • 自创的机械臂新算法,因为是AI写的,暂时,并不智能,但目前支持任何段数
  • 图解说明电源管理芯片在嵌入式系统中的作用
  • 2025智能体安全实践报告 清华大学(附下载)
  • 基于CCS的报警管理系统:完整示例
  • elasticsearch可视化工具实现集群负载均衡监控教程
  • LangFlow古诗词风格迁移写作工具
  • 基于Raspberry Pi Imager的树莓派4b系统安装全过程记录
  • CCS20中数据对齐优化对性能提升的实测报告
  • USB转串口驱动安装新手教程:从下载到配置全流程
  • LangFlow养生食谱个性化推荐引擎
  • Windows下Arduino安装教程:从下载到IDE配置手把手指导
  • UUID vs 自增ID做主键,哪个好?
  • SQL INSERT INTO SELECT 语句
  • LangFlow合同条款审查辅助工具实现
  • 门电路输入漏电流影响:通俗解释高阻态稳定性
  • 智能算法加持!婚恋交友源码系统开发,uni+php成品系统多端同步,小程序 / H5/APP 数据互通,二次开发 + 售后指导
  • Java面试官怒怼水货程序员:Spring Cloud微服务+Kafka消息队列+Redis缓存,你到底会不会?
  • 【API 设计之道】08 流量与配额:构建基于 Redis 的分布式限流器
  • LangFlow体检报告解读助手设计思路
  • 零基础掌握用iverilog做数字电路仿真的关键步骤
  • 从单点充电到全域智控:安科瑞重塑新能源充电生态
  • 图解说明Altium Designer高速信号回流路径设计
  • 2025年中国电缆一线品牌推荐:中国电缆知名品牌盘点,缆标杆品牌推荐(12月更新) - 品牌2026
  • 全自研仿真GPU求解器x虚实对标物理测量工厂,打造具身合成数据SuperApp,加速具身仿真生态丨光轮智能@MEET2026
  • STM32CubeMX无法打开:新手教程之Windows权限设置