最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Vue 3 TypeScript 接口Interface使用示例詳解

 更新時間:2025年07月18日 10:47:21   作者:m0_61618849  
Vue3中TypeScript的接口用于定義組件props、數(shù)據(jù)模型、事件等類型結(jié)構(gòu),提升代碼可讀性與維護(hù)性,常見場景包括props類型、響應(yīng)式數(shù)據(jù)、狀態(tài)對象、事件類型等,本文給大家介紹Vue 3 TypeScript接口Interface使用示例,感興趣的朋友一起看看吧

在 Vue 3 中使用 TypeScript 時,接口(Interface)是定義類型的重要工具。接口可以幫助我們明確組件 props、數(shù)據(jù)模型、函數(shù)簽名等內(nèi)容的類型結(jié)構(gòu),提高代碼可讀性和可維護(hù)性。

接口在 Vue 3 中的常見應(yīng)用場景

1. 定義組件 Props 類型

// 用戶信息接口
interface User {
  id: number;
  name: string;
  email: string;
  age?: number; // 可選屬性
}
// 在組件中使用
export default defineComponent({
  props: {
    // 使用接口定義props類型
    user: {
      type: Object as () => User, // 類型斷言
      required: true
    },
    // 簡單類型
    isActive: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    // 現(xiàn)在可以安全訪問props.user的屬性
    const userName = computed(() => props.user.name);
    return { userName };
  }
});

2. 定義響應(yīng)式數(shù)據(jù)模型

// 待辦事項(xiàng)接口
interface TodoItem {
  id: number;
  title: string;
  completed: boolean;
  createdAt: Date;
}
export default defineComponent({
  setup() {
    // 使用接口定義響應(yīng)式數(shù)據(jù)
    const todos = ref<TodoItem[]>([
      {
        id: 1,
        title: '學(xué)習(xí) Vue 3',
        completed: false,
        createdAt: new Date()
      }
    ]);
    // 添加新待辦事項(xiàng)的函數(shù)
    const addTodo = (title: string) => {
      const newTodo: TodoItem = {
        id: Date.now(),
        title,
        completed: false,
        createdAt: new Date()
      };
      todos.value.push(newTodo);
    };
    return { todos, addTodo };
  }
});

3. 定義復(fù)雜的狀態(tài)對象

// 應(yīng)用狀態(tài)接口
interface AppState {
  isLoading: boolean;
  error: string | null;
  data: any[];
  page: number;
}
export default defineComponent({
  setup() {
    // 使用接口定義狀態(tài)對象
    const state = reactive<AppState>({
      isLoading: false,
      error: null,
      data: [],
      page: 1
    });
    // 獲取數(shù)據(jù)的方法
    const fetchData = async () => {
      state.isLoading = true;
      state.error = null;
      try {
        const response = await fetch(`/api/data?page=${state.page}`);
        state.data = await response.json();
      } catch (err) {
        state.error = '獲取數(shù)據(jù)失敗';
      } finally {
        state.isLoading = false;
      }
    };
    return { state, fetchData };
  }
});

4. 定義事件發(fā)射類型

// 自定義事件接口
interface CustomEvents {
  (e: 'update:name', value: string): void;
  (e: 'delete', id: number): void;
}
export default defineComponent({
  emits: ['update:name', 'delete'] as unknown as CustomEvents,
  setup(props, { emit }) {
    const updateName = (newName: string) => {
      // 類型安全的事件發(fā)射
      emit('update:name', newName);
    };
    const deleteItem = (id: number) => {
      // 類型安全的事件發(fā)射
      emit('delete', id);
    };
    return { updateName, deleteItem };
  }
});

5. 定義組合函數(shù)類型

// 計數(shù)器組合函數(shù)接口
interface Counter {
  count: Ref<number>;
  increment: () => void;
  decrement: () => void;
  reset: () => void;
}
// 創(chuàng)建計數(shù)器的組合函數(shù)
export function useCounter(initialValue = 0): Counter {
  const count = ref(initialValue);
  const increment = () => count.value++;
  const decrement = () => count.value--;
  const reset = () => count.value = initialValue;
  return { count, increment, decrement, reset };
}

6. 定義 API 響應(yīng)類型

// API 響應(yīng)接口
interface ApiResponse<T> {
  status: 'success' | 'error';
  message: string;
  data: T;
  timestamp: Date;
}
// 用戶數(shù)據(jù)接口
interface UserData {
  id: number;
  name: string;
  email: string;
}
// 在組件中使用
export default defineComponent({
  setup() {
    const userData = ref<UserData | null>(null);
    const fetchUser = async (id: number) => {
      const response = await fetch(`/api/users/${id}`);
      const result: ApiResponse<UserData> = await response.json();
      if (result.status === 'success') {
        userData.value = result.data;
      }
    };
    return { userData, fetchUser };
  }
});

接口高級用法

1. 接口繼承

// 基礎(chǔ)實(shí)體接口
interface BaseEntity {
  id: number;
  createdAt: Date;
  updatedAt: Date;
}
// 用戶接口繼承基礎(chǔ)實(shí)體
interface User extends BaseEntity {
  name: string;
  email: string;
  role: 'admin' | 'user';
}
// 產(chǎn)品接口繼承基礎(chǔ)實(shí)體
interface Product extends BaseEntity {
  name: string;
  price: number;
  description: string;
  category: string;
}

2. 索引簽名

// 字典接口
interface Dictionary<T> {
  [key: string]: T;
}
// 在組件中使用
const colors: Dictionary<string> = {
  primary: '#3498db',
  secondary: '#2ecc71',
  danger: '#e74c3c'
};
const permissions: Dictionary<boolean> = {
  canEdit: true,
  canDelete: false,
  canCreate: true
};

3. 函數(shù)類型接口

// 比較函數(shù)接口
interface Comparator<T> {
  (a: T, b: T): number;
}
// 在組件中使用
const sortUsers = (users: User[], comparator: Comparator<User>) => {
  return [...users].sort(comparator);
};
// 創(chuàng)建比較器
const byName: Comparator<User> = (a, b) => a.name.localeCompare(b.name);
const byDate: Comparator<User> = (a, b) => 
  a.createdAt.getTime() - b.createdAt.getTime();

完整示例:使用接口的 Vue 3 組件

<template>
  <div class="user-profile">
    <h2>{{ user.name }}</h2>
    <p>郵箱: {{ user.email }}</p>
    <p v-if="user.age">年齡: {{ user.age }}</p>
    <div class="stats">
      <div class="stat-item">
        <span class="stat-label">文章數(shù):</span>
        <span class="stat-value">{{ stats.postCount }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">關(guān)注者:</span>
        <span class="stat-value">{{ stats.followerCount }}</span>
      </div>
    </div>
    <button @click="updateName">更新用戶名</button>
  </div>
</template>
<script lang="ts">
import { defineComponent, PropType, reactive } from 'vue';
// 定義用戶接口
interface User {
  id: number;
  name: string;
  email: string;
  age?: number;
}
// 定義用戶統(tǒng)計數(shù)據(jù)接口
interface UserStats {
  postCount: number;
  followerCount: number;
  followingCount: number;
}
export default defineComponent({
  props: {
    user: {
      type: Object as PropType<User>,
      required: true
    }
  },
  setup(props, { emit }) {
    // 使用接口定義響應(yīng)式狀態(tài)
    const stats = reactive<UserStats>({
      postCount: 24,
      followerCount: 128,
      followingCount: 56
    });
    // 更新用戶名的函數(shù)
    const updateName = () => {
      const newName = prompt('請輸入新的用戶名:');
      if (newName) {
        // 發(fā)射自定義事件
        emit('update:name', newName);
      }
    };
    return { stats, updateName };
  }
});
</script>
<style scoped>
.user-profile {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #e1e1e1;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
h2 {
  color: #2c3e50;
  margin-bottom: 10px;
}
p {
  color: #7f8c8d;
  margin: 5px 0;
}
.stats {
  display: flex;
  margin: 20px 0;
  border-top: 1px solid #eee;
  padding-top: 15px;
}
.stat-item {
  flex: 1;
  text-align: center;
}
.stat-label {
  display: block;
  color: #95a5a6;
  font-size: 0.9rem;
}
.stat-value {
  display: block;
  font-size: 1.5rem;
  font-weight: bold;
  color: #3498db;
}
button {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s;
}
button:hover {
  background-color: #2980b9;
}
</style>

到此這篇關(guān)于Vue 3 TypeScript 接口(Interface)使用的文章就介紹到這了,更多相關(guān)Vue TypeScript 接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Vue后臺中優(yōu)雅書寫狀態(tài)標(biāo)簽的方法實(shí)例

    Vue后臺中優(yōu)雅書寫狀態(tài)標(biāo)簽的方法實(shí)例

    在Vue中,我們可以非常便捷地通過標(biāo)簽實(shí)現(xiàn)狀態(tài)的保存,這篇文章主要給大家介紹了關(guān)于Vue后臺中如何優(yōu)雅的書寫狀態(tài)標(biāo)簽的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2021-08-08
  • Vue3中watchEffect和watch的基礎(chǔ)應(yīng)用詳解

    Vue3中watchEffect和watch的基礎(chǔ)應(yīng)用詳解

    watch是一個偵聽器,默認(rèn)是懶偵聽的,即僅在偵聽源發(fā)生變化時才執(zhí)行回調(diào)函數(shù),watchEffect是會自動收集函數(shù)里面變量的響應(yīng)式依賴,本文主要來講講二者的區(qū)別,感興趣的可以了解一下
    2023-07-07
  • vue項(xiàng)目中使用rimraf?dev啟動時刪除dist目錄方式

    vue項(xiàng)目中使用rimraf?dev啟動時刪除dist目錄方式

    這篇文章主要介紹了vue項(xiàng)目中使用rimraf?dev啟動時刪除dist目錄方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • vue3+Element采用遞歸調(diào)用封裝導(dǎo)航欄實(shí)現(xiàn)

    vue3+Element采用遞歸調(diào)用封裝導(dǎo)航欄實(shí)現(xiàn)

    本文主要介紹了vue3+Element采用遞歸調(diào)用封裝導(dǎo)航欄,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • 利用vite創(chuàng)建vue3項(xiàng)目的全過程及一個小BUG詳解

    利用vite創(chuàng)建vue3項(xiàng)目的全過程及一個小BUG詳解

    Vite作為一個構(gòu)建工具,提供了一種快速的方法來構(gòu)建Vue應(yīng)用,而Vue3?則是一個前端框架,提供了強(qiáng)大的功能來構(gòu)建和管理前端項(xiàng)目,下面這篇文章主要給大家介紹了關(guān)于利用vite創(chuàng)建vue3項(xiàng)目的全過程及一個小BUG的相關(guān)資料,需要的朋友可以參考下
    2023-04-04
  • vue如何跳轉(zhuǎn)到其他頁面

    vue如何跳轉(zhuǎn)到其他頁面

    跳轉(zhuǎn)到指定URL,向history棧添加一個新的紀(jì)錄,點(diǎn)擊后退會返回至上一個頁面,這篇文章給大家介紹vue如何跳轉(zhuǎn)到其他頁面,包括無參跳轉(zhuǎn)和帶參跳轉(zhuǎn),本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧
    2023-10-10
  • vue 實(shí)現(xiàn)在函數(shù)中觸發(fā)路由跳轉(zhuǎn)的示例

    vue 實(shí)現(xiàn)在函數(shù)中觸發(fā)路由跳轉(zhuǎn)的示例

    今天小編就為大家分享一篇vue 實(shí)現(xiàn)在函數(shù)中觸發(fā)路由跳轉(zhuǎn)的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-09-09
  • Vue中的局部組件介紹

    Vue中的局部組件介紹

    這篇文章主要介紹了Vue中的局部組件,文章圍繞Vue局部組件得相關(guān)資料展開內(nèi)容,需要的的小孩伙伴請參考下面文章的具體介紹,希望對你有所幫助
    2021-12-12
  • 一文詳解vue3?watchEffect監(jiān)聽的各種姿勢用法

    一文詳解vue3?watchEffect監(jiān)聽的各種姿勢用法

    watchEffect 會自動追蹤在其回調(diào)函數(shù)中使用的所有響應(yīng)式依賴,無需顯式指定數(shù)據(jù)源,本文將為大家總結(jié)一下vue3?watchEffect監(jiān)聽的各種用法,有需要的可以了解下
    2026-03-03
  • Vue.js路由實(shí)現(xiàn)選項(xiàng)卡簡單實(shí)例

    Vue.js路由實(shí)現(xiàn)選項(xiàng)卡簡單實(shí)例

    這篇文章主要為大家詳細(xì)介紹了Vue.js路由實(shí)現(xiàn)選項(xiàng)卡簡單實(shí)例,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-07-07

最新評論

双牌县| 乌兰浩特市| 喀喇| 集安市| 汽车| 肃南| 吉林省| 景洪市| 若羌县| 泾阳县| 保定市| 武义县| 东阿县| 平定县| 临汾市| 琼海市| 白沙| 荆州市| 华亭县| 太原市| 响水县| 鄂伦春自治旗| 华坪县| 综艺| 宁强县| 嘉兴市| 彰化市| 苍梧县| 拉萨市| 尚志市| 八宿县| 伊通| 秭归县| 彭水| 呼和浩特市| 双鸭山市| 全南县| 通山县| 珲春市| 岢岚县| 广西|