一句话总结:没有想象中那么难用
一、关于工具插件:
- 使用vs code的话建议安装Volar,开发起来提示很方便
- 如果安装了vetur,建议设置中搜索vetur,找到Validate js/ts in,把勾去掉
二、关于开发
-
在项目中我是采用
<script lang="ts" setup>这样的方式开发,比之前的写法简洁太多了,再也不用return一堆东西出去了,引用组件也不用那么麻烦了。 -
最大的感受就是要写一堆interface(可以抽取一些出来做个公用的interface)
举个例子
export interface TableData { total: number; tableData: Array<object>; }import {TableData} from xxxxx const table = reactive<TableData>({ total: 0, tableData: [], }); -
定义变量和写方法的参数时,最好加上类型定义。
const pageNum = ref<number>(1);const handleCurrentChange = (num:number) => { pageNum.value = num; }; -
采用setup放在script的方式的话,父子通讯的写法也稍微有点变化
父组件:
<template> <div class="home"> <HelloWorld msg="Welcome to Your Vue.js + TypeScript App" @getChild="getChild" /> </div> </template> <script lang="ts" setup> import HelloWorld from "@/components/HelloWorld.vue"; const getChild = (e:string) => { // 接收父组件传递过来的数据 console.log(e); // child value }; </script>子组件:
<template> <div> <div>{{ props.msg }}</div> <el-button @click="toEmits">向父组件传递数据</el-button> </div> </template> <script lang="ts" setup> import { reactive, ref } from "vue"; const props = defineProps({ msg: { type: String, default: "default message", }, }); const emits = defineEmits(["getChild"]); const toEmits = () => { emits("getChild", "child value"); // 向父组件传递数据 }; </script> -
这次项目里没用到自定义hook,但这个技术我觉得还是挺好的,作用类似于vue2中的mixin技术,之后了解后可以再出篇文章