Loading...

Vue 與 Typescript 的應用

這篇文章探討了使用Vue和TypeScript開發應用程序時的不同選項和技術。它涵蓋了Options API和Composition API兩種不同的開發方式,並介紹了如何使用Interface和Type Alias來定義類型。

更新於 2025-03-13 08:53:39
Written by   Jacky Yang@Jacky Yang

Options api 的應用

可以在key後面直接加入 type

  data(){
    return {
      name: 'Vue3',
      age: 25 as string | number // 定義為 string 或 number
    }
  },

如果使用此key傳入不對的type就會出現錯誤

Composition API 的應用

如果使用ref()指定型別的話就要使用泛型( Generics )或是類型斷言(Type Assertion)

  setup(){
    const name = ref('Vue3')
    const age = ref<string|number>('rseresr') // 泛型
    // const age = ref('rseresr') as Ref<string|number>; // 類型斷言(Type Assertion)
    return {
      name,
      age
    }
  },


自訂義型別別名(type alias)

可以自訂義型別,然後export default出去,此範例為設定排列方式只能是"location" 、"salary"、"title"

// OrderTerm.ts

type OrderTerm = 'location' | 'salary' | 'title';

export default OrderTerm;

在App.vue中使用OrderTerm alias

// App.vue
import OrderTerm from './types/OrderTerm';
setup(){
    const order = ref<OrderTerm>('title')  // 使用OrderTerm alias
    const handleClick = (term: OrderTerm) => {
      order.value = term
    }
    return {
      jobs,handleClick,order
    }
},

如果將order的預設值改成id會出現錯誤:

介面(Interface)

我們可以定義一個物件的屬性,一樣export default出去

// Job.ts
interface Job {
    id: string,
    title: string,
    location: string,
    salary: number,
}
export default Job;

接下來在App.vue setup()中定義一個jobs ref,並使用Job 這個泛型,並且設定他是一個Array

// App.vue setup()

import Job from './types/Job';
const jobs = ref<Job[]>([
  {
    id:'1',
    title: 'Clean the dishes',
    salary: 50000,
    location: 'Death Mountain'
  },
  {
    id:'2',
    title: 'Wash the car',
    salary: 30000,
    location: 'Gerudo Valley'
  },
  {
    id:'3',
    title: 'Save the princess',
    salary: 10000,
    location: 'Hyrule Castle'
  },
  {
    id:'4',
    title: 'Defeat Ganon',
    salary: 100000,
    location: `on top of Hyrule Castle's sky`
  },
])