typescript语法及小例子,vue3

382 阅读3分钟

1.为什么采用VUE3?

  1. VUE3打包快,渲染快
  2. vue3采用composition API 3有teleporat等特性,对TS等特性更加支持。
  3. 支持hooks,让vue项目复用更加简单
  4. setup函数中可以分功能来写代码,逻辑更加清晰 在ant design与vue3,typescript的环境中,业务为一个普通表单。

定义变量

ref的结构

使用条件: 原始值[字符串,布尔值]应该使用ref。ref返回的是一个可变的响应式对象,该对象只包含一个名为value的property

ref解包: ref声明的变量不需要在模板中用.value获取,因为ref在模板中是被自动浅解包。 JSX中依然需要.value获取

eg: var isShowDialog=ref(false) 这其中就用了类型断言 <> <>表示确定这个变量的类型,无需TS进行校验。

<div v-if="isShowDialog"></div>
 var isShowDialog=ref<boolean>(false)
const showDialog=()=>{ isShowDialog.value=true}

let isShow:boolean=false;

let count:number=0;

let a:string='a'

let arrNum:number[]=[1,2,3]

定义函数时候不需要传参,可以直接箭头函数。

const ok=()=>{isShow.value=true } //ref要改变的时候要用.value赋值

TS中的interface 接口可以规定这个变量包括那些属性。1. ?表示参数可选2. 函数接口

interface human{
    readonly:name:string
    sex?:string
}
let jack:Human={
    name:'jack'
}
interface Human extends Animal {
    name: string;
    age: number;
}

toRefs的运用

toRefs的本质是 讲响应式对象转为结果对象,其中结果对象的每个属性都是指向原始对象属性对应的ref. 所以解构解析出来的值 x,获取值为x.value

何时使用toRefs? 在用reactive定义一个对象后,想获取对象属性就要用toRefs结构解析

export defineComponent({
props:[title],
setup(props){
//解构赋值会导致对象失去响应
const {title}=toRefs(props)
console.log(1,title.value)

reactive+toRefs

模板中使用tile,要写state.title略显麻烦,可以用toRefs()来解包用reactive定义的对象。然后用...扩展运算符来解构对象~

const state=reactive({title:'aa'})
return {...toRefs(state),others}

computed

vue3需要单独定义用computed函数,利用箭头函数返回。并在steup函数中返回该computed的变量。 computed接受一个getter,为这个getter的返回值返回一个不可变的响应式ref对象。

 const filterTodoList = computed(() => {
      switch (filterStatus.value) {
        case "finish":
          return todoList.value.filter((item) => item.finished);
        case 'notFinish':
          return todoList.value.filter((item) => !item.finished);
        default:
          return todoList.value;
      }
    });

watch

vue2版本与vue3版本的差异就在于,vue2的watch卸载wacth对象之中。

vue3 直接写在watch函数中即可。

  1. 监听一个参数: watch( ,(newValue,oldValue))watch中第一个参数是你要监听的参数名称,第二个参数是 (newValue,oldValue)
  2. 监听多个参数:第一个参数是数组。 watch([a,b,c],(newValues,oldValues)=>{}) 监听响应式对象 监听数组或者对象,要求有一份副本。
watch(
  () => [...numbers],
  (numbers, prevNumbers) => {
    console.log(numbers, prevNumbers)
  }
)
  1. 检查深度嵌套对象或者数组监听需要设置deep:true
watch(
  () => state,
  (state, prevState) => {
    console.log('deep', state.attributes.name, prevState.attributes.name)
  },
  { deep: true }
)

vue3TS支持

定义vue组件

定义组件要用defineComponent定义组件const component=defineComponent({})

选项式API

注解返回类型

vue需要声明computed的返回类型

props

注解props, vue对定义了类型的prop进行验证,需要将这些类型提供给typescript,我们使用propType致命构造函数。

const greeting:String=cpmputed(()=>'sdd')
interface Book {
  title: String;
  author: String;
  year: number;
}
export const a = defineComponent({
  props: {
    success: { type: String },
    callback: {
      type: Function as PropType<() => void>,
    },
    book: {
      type: Object as PropType<Book>,
      required: true,
    },
  },
});

组合式API

1.在setup函数中,不需要将类型传递给props参数,因为它将从prop中推断类型。 2.为事件处理器添加类型

      const handleChange = (evt: Event) => {
        console.log(evt.target.value)
    }

在setup函数中访问路由和当前路由

import { useRouter, useRoute } from 'vue-router'
export default {
  setup() {
    const router = useRouter();
    const route = useRoute();
    const pushQuery = () => {
      router.push({
        name: 'Search',
        query:{...route.query}
      })
    }
  }
}