Vue3從入門到精通(三)

来源:https://www.cnblogs.com/for-easy-fast/archive/2023/06/30/17515670.html
-Advertisement-
Play Games

vue3插槽Slots 在 Vue3 中,插槽(Slots)的使用方式與 Vue2 中基本相同,但有一些細微的差異。以下是在 Vue3 中使用插槽的示例: // ChildComponent.vue <template> <div> <h2>Child Component</h2> <slot></ ...


vue3插槽Slots

在 Vue3 中,插槽(Slots)的使用方式與 Vue2 中基本相同,但有一些細微的差異。以下是在 Vue3 中使用插槽的示例:

// ChildComponent.vue
<template>
  <div>
    <h2>Child Component</h2>
    <slot></slot>
  </div>
</template>
​
// ParentComponent.vue
<template>
  <div>
    <h1>Parent Component</h1>
    <ChildComponent>
      <p>This is the content of the slot.</p>
    </ChildComponent>
  </div>
</template>
​
<script>
  import { defineComponent } from 'vue'
  import ChildComponent from './ChildComponent.vue'
​
  export default defineComponent({
    name: 'ParentComponent',
    components: {
      ChildComponent
    }
  })
</script>

在上面的示例中,ChildComponent 組件定義了一個預設插槽,使用 <slot></slot> 標簽來表示插槽的位置。在 ParentComponent 組件中,使用 <ChildComponent> 標簽包裹了一段內容 <p>This is the content of the slot.</p>,這段內容將被插入到 ChildComponent 組件的插槽位置。

需要註意的是,在 Vue3 中,預設插槽不再具有具名插槽的概念。如果需要使用具名插槽,可以使用 v-slot 指令。以下是一個示例:

// ChildComponent.vue
<template>
  <div>
    <h2>Child Component</h2>
    <slot name="header"></slot>
    <slot></slot>
    <slot name="footer"></slot>
  </div>
</template>
​
// ParentComponent.vue
<template>
  <div>
    <h1>Parent Component</h1>
    <ChildComponent>
      <template v-slot:header>
        <h3>This is the header slot</h3>
      </template>
      <p>This is the content of the default slot.</p>
      <template v-slot:footer>
        <p>This is the footer slot</p>
      </template>
    </ChildComponent>
  </div>
</template>
​
<script>
  import { defineComponent } from 'vue'
  import ChildComponent from './ChildComponent.vue'
​
  export default defineComponent({
    name: 'ParentComponent',
    components: {
      ChildComponent
    }
  })
</script>

在上面的示例中,ChildComponent 組件定義了三個插槽,分別是名為 header、預設插槽和名為 footer 的插槽。在 ParentComponent 組件中,使用 <template v-slot:header> 來定義 header 插槽的內容,使用 <template v-slot:footer> 來定義 footer 插槽的內容。預設插槽可以直接寫在組件標簽內部。

需要註意的是,在 Vue3 中,v-slot 只能用在 <template> 標簽上,不能用在普通的 HTML 標簽上。如果要在普通 HTML 標簽上使用插槽,可以使用 v-slot 的縮寫語法 #。例如,<template v-slot:header> 可以簡寫為 #header

vue3組件生命周期

在 Vue3 中,組件的生命周期鉤子函數與 Vue2 中有一些變化。以下是 Vue3 中常用的組件生命周期鉤子函數:

  1. beforeCreate: 在實例初始化之後、數據觀測之前被調用。

  2. created: 在實例創建完成之後被調用。此時,實例已完成數據觀測、屬性和方法的運算,但尚未掛載到 DOM 中。

  3. beforeMount: 在掛載開始之前被調用。在此階段,模板已經編譯完成,但尚未將模板渲染到 DOM 中。

  4. mounted: 在掛載完成之後被調用。此時,組件已經被掛載到 DOM 中,可以訪問到 DOM 元素。

  5. beforeUpdate: 在數據更新之前被調用。在此階段,虛擬 DOM 已經重新渲染,並將計算得到的變化應用到真實 DOM 上,但尚未更新到視圖中。

  6. updated: 在數據更新之後被調用。此時,組件已經更新到最新的狀態,DOM 也已經更新完成。

  7. beforeUnmount: 在組件卸載之前被調用。在此階段,組件實例仍然可用,可以訪問到組件的數據和方法。

  8. unmounted: 在組件卸載之後被調用。此時,組件實例已經被銷毀,無法再訪問到組件的數據和方法。

需要註意的是,Vue3 中移除了一些生命周期鉤子函數,如 beforeDestroydestroyed。取而代之的是 beforeUnmountunmounted

另外,Vue3 中還引入了新的生命周期鉤子函數 onRenderTrackedonRenderTriggered,用於追蹤組件的渲染過程和觸發的依賴項。

需要註意的是,Vue3 推薦使用 Composition API 來編寫組件邏輯,而不是依賴於生命周期鉤子函數。Composition API 提供了 setup 函數,用於組件的初始化和邏輯組織。在 setup 函數中,可以使用 onBeforeMountonMountedonBeforeUpdateonUpdatedonBeforeUnmount 等函數來替代相應的生命周期鉤子函數。

vue3生命周期應用

Vue3 的生命周期鉤子函數可以用於在組件的不同生命周期階段執行相應的操作。以下是一些 Vue3 生命周期的應用場景示例:

  1. beforeCreatecreated:在組件實例創建之前和創建之後執行一些初始化操作,如設置初始數據、進行非同步請求等。

export default {
  beforeCreate() {
    console.log('beforeCreate hook');
    // 執行一些初始化操作
  },
  created() {
    console.log('created hook');
    // 執行一些初始化操作
  },
};
  1. beforeMountmounted:在組件掛載之前和掛載之後執行一些 DOM 操作,如獲取 DOM 元素、綁定事件等。

export default {
  beforeMount() {
    console.log('beforeMount hook');
    // 執行一些 DOM 操作
  },
  mounted() {
    console.log('mounted hook');
    // 執行一些 DOM 操作
  },
};
  1. beforeUpdateupdated:在組件數據更新之前和更新之後執行一些操作,如更新 DOM、發送請求等。

export default {
  beforeUpdate() {
    console.log('beforeUpdate hook');
    // 執行一些操作
  },
  updated() {
    console.log('updated hook');
    // 執行一些操作
  },
};
  1. beforeUnmountunmounted:在組件卸載之前和卸載之後執行一些清理操作,如取消訂閱、清除定時器等。

export default {
  beforeUnmount() {
    console.log('beforeUnmount hook');
    // 執行一些清理操作
  },
  unmounted() {
    console.log('unmounted hook');
    // 執行一些清理操作
  },
};

這些示例展示了 Vue3 生命周期鉤子函數的一些常見應用場景。根據具體需求,你可以在相應的生命周期鉤子函數中執行適當的操作。

vue3動態組件

在 Vue3 中,可以使用動態組件來根據不同的條件或狀態動態地渲染不同的組件。使用動態組件可以使應用更加靈活和可擴展。以下是使用動態組件的示例:

  1. 使用 component 元素和 :is 屬性來實現動態組件的渲染:

<template>
  <div>
    <component :is="currentComponent"></component>
    <button @click="toggleComponent">Toggle Component</button>
  </div>
</template>
​
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
​
export default {
  data() {
    return {
      currentComponent: 'ComponentA',
    };
  },
  methods: {
    toggleComponent() {
      this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA';
    },
  },
  components: {
    ComponentA,
    ComponentB,
  },
};
</script>

在上面的示例中,根據 currentComponent 的值動態地渲染 ComponentAComponentB 組件。點擊按鈕時,切換 currentComponent 的值,從而實現動態組件的切換。

  1. 使用 v-ifv-else 來根據條件渲染不同的組件:

<template>
  <div>
    <component-a v-if="showComponentA"></component-a>
    <component-b v-else></component-b>
    <button @click="toggleComponent">Toggle Component</button>
  </div>
</template>
​
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
​
export default {
  data() {
    return {
      showComponentA: true,
    };
  },
  methods: {
    toggleComponent() {
      this.showComponentA = !this.showComponentA;
    },
  },
  components: {
    ComponentA,
    ComponentB,
  },
};
</script>

在上面的示例中,根據 showComponentA 的值使用 v-ifv-else 來渲染 ComponentAComponentB 組件。點擊按鈕時,切換 showComponentA 的值,從而實現動態組件的切換。

這些示例演示了在 Vue3 中如何使用動態組件來根據條件或狀態動態地渲染不同的組件。你可以根據具體需求選擇適合的方式來使用動態組件。

vue3組件保持存活

在 Vue3 中,可以使用 <keep-alive> 組件來保持組件的存活狀態,即使組件在組件樹中被切換或銷毀,它的狀態仍然會被保留。這對於需要在組件之間共用狀態或緩存數據的場景非常有用。以下是使用 <keep-alive> 組件來保持組件存活的示例:

<template>
  <div>
    <button @click="toggleComponent">Toggle Component</button>
    <keep-alive>
      <component :is="currentComponent"></component>
    </keep-alive>
  </div>
</template>
​
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
​
export default {
  data() {
    return {
      currentComponent: 'ComponentA',
    };
  },
  methods: {
    toggleComponent() {
      this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA';
    },
  },
  components: {
    ComponentA,
    ComponentB,
  },
};
</script>

在上面的示例中,使用 <keep-alive> 組件將 <component> 包裹起來,這樣在切換組件時,被包裹的組件的狀態將會被保留。點擊按鈕時,切換 currentComponent 的值,從而切換要渲染的組件。

需要註意的是,被 <keep-alive> 包裹的組件在切換時會觸發一些特定的生命周期鉤子函數,如 activateddeactivated。你可以在這些鉤子函數中執行一些特定的操作,如獲取焦點、發送請求等。

<template>
  <div>
    <h2>Component A</h2>
  </div>
</template>
​
<script>
export default {
  activated() {
    console.log('Component A activated');
    // 執行一些操作
  },
  deactivated() {
    console.log('Component A deactivated');
    // 執行一些操作
  },
};
</script>

在上面的示例中,當組件 A 被激活或停用時,分別在 activateddeactivated 鉤子函數中輸出相應的信息。

使用 <keep-alive> 組件可以方便地保持組件的存活狀態,併在組件之間共用狀態或緩存數據。

vue3非同步組件

在 Vue3 中,可以使用非同步組件來延遲載入組件的代碼,從而提高應用的性能和載入速度。非同步組件在需要時才會被載入,而不是在應用初始化時就載入所有組件的代碼。以下是使用非同步組件的示例:

  1. 使用 defineAsyncComponent 函數來定義非同步組件:

<template>
  <div>
    <button @click="loadComponent">Load Component</button>
    <component v-if="isComponentLoaded" :is="component"></component>
  </div>
</template>
​
<script>
import { defineAsyncComponent } from 'vue';
​
const AsyncComponent = defineAsyncComponent(() =>
  import('./Component.vue')
);
​
export default {
  data() {
    return {
      isComponentLoaded: false,
      component: null,
    };
  },
  methods: {
    loadComponent() {
      this.isComponentLoaded = true;
      this.component = AsyncComponent;
    },
  },
};
</script>

在上面的示例中,使用 defineAsyncComponent 函數來定義非同步組件 AsyncComponent。當點擊按鈕時,設置 isComponentLoadedtrue,並將 component 設置為 AsyncComponent,從而載入非同步組件。

  1. 使用 Suspense 組件來處理非同步組件的載入狀態:

<template>
  <div>
    <Suspense>
      <template #default>
        <component :is="component"></component>
      </template>
      <template #fallback>
        <div>Loading...</div>
      </template>
    </Suspense>
    <button @click="loadComponent">Load Component</button>
  </div>
</template>
​
<script>
import { defineAsyncComponent, Suspense } from 'vue';
​
const AsyncComponent = defineAsyncComponent(() =>
  import('./Component.vue')
);
​
export default {
  data() {
    return {
      component: null,
    };
  },
  methods: {
    loadComponent() {
      this.component = AsyncComponent;
    },
  },
};
</script>

在上面的示例中,使用 Suspense 組件來處理非同步組件的載入狀態。在 default 插槽中,渲染非同步組件,而在 fallback 插槽中,渲染載入狀態的提示信息。當點擊按鈕時,載入非同步組件。

這些示例演示了在 Vue3 中如何使用非同步組件來延遲載入組件的代碼。使用非同步組件可以提高應用的性能和載入速度,特別是在應用中有大量組件時。

vue3依賴註入

在 Vue3 中,可以使用依賴註入來在組件之間共用數據或功能。Vue3 提供了 provideinject 兩個函數來實現依賴註入。

  1. 使用 provide 函數在父組件中提供數據或功能:

<template>
  <div>
    <ChildComponent></ChildComponent>
  </div>
</template>
​
<script>
import { provide } from 'vue';
import MyService from './MyService';
​
export default {
  setup() {
    provide('myService', new MyService());
  },
};
</script>

在上面的示例中,使用 provide 函數在父組件中提供了一個名為 myService 的數據或功能,它的值是一個 MyService 的實例。

  1. 使用 inject 函數在子組件中註入提供的數據或功能:

<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>
​
<script>
import { inject } from 'vue';
​
export default {
  setup() {
    const myService = inject('myService');
    const message = myService.getMessage();
​
    return {
      message,
    };
  },
};
</script>

在上面的示例中,使用 inject 函數在子組件中註入了父組件提供的名為 myService 的數據或功能。通過註入的 myService 實例,可以調用其中的方法或訪問其中的屬性。

通過使用 provideinject 函數,可以在組件之間實現依賴註入,從而實現數據或功能的共用。這在多個組件需要訪問相同的數據或功能時非常有用。

vue3應用

Vue3 是一個用於構建用戶界面的現代化 JavaScript 框架。它具有響應式數據綁定、組件化、虛擬 DOM 等特性,使得開發者可以更高效地構建互動式的 Web 應用。

下麵是一些使用 Vue3 開發應用的步驟:

  1. 安裝 Vue3:使用 npm 或 yarn 安裝 Vue3 的最新版本。

npm install vue@next
  1. 創建 Vue3 應用:創建一個新的 Vue3 項目。

vue create my-app
  1. 編寫組件:在 src 目錄下創建組件文件,例如 HelloWorld.vue

<template>
  <div>
    <h1>{{ message }}</h1>
    <button @click="changeMessage">Change Message</button>
  </div>
</template>
​
<script>
import { ref } from 'vue';
​
export default {
  setup() {
    const message = ref('Hello, Vue3!');
​
    const changeMessage = () => {
      message.value = 'Hello, World!';
    };
​
    return {
      message,
      changeMessage,
    };
  },
};
</script>

在上面的示例中,使用 ref 函數創建了一個響應式的數據 message,併在模板中使用它。通過點擊按鈕,可以改變 message 的值。

  1. 使用組件:在 App.vue 中使用自定義的組件。

<template>
  <div>
    <HelloWorld></HelloWorld>
  </div>
</template>
​
<script>
import HelloWorld from './components/HelloWorld.vue';
​
export default {
  components: {
    HelloWorld,
  },
};
</script>

在上面的示例中,導入並註冊了自定義的 HelloWorld 組件,併在模板中使用它。

  1. 運行應用:在命令行中運行以下命令啟動應用。

npm run serve

這將啟動開發伺服器,併在瀏覽器中打開應用。

這隻是一個簡單的示例,你可以根據實際需求編寫更複雜的組件和應用邏輯。Vue3 還提供了許多其他功能和工具,如路由、狀態管理、單文件組件等,以幫助你構建更強大的應用。

希望這個簡單的示例能幫助你入門 Vue3 應用的開發!

付費內容,請聯繫本人QQ:1002453261

本文來自博客園,作者:明志德道,轉載請註明原文鏈接:https://www.cnblogs.com/for-easy-fast/p/17515670.html


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Kafka 的核心功能是高性能的消息發送與高性能的消息消費。Kafka 名字的由來是 Kafka 三位原作者之一 Jay Kreps 說 Kafka 系統充分優化了寫操作,所以用一個作家的名字來命名很有意義,他非常喜歡作家 Franz Kafka,並且用 Kafka 命名開源項目很酷 。本文是 Ka... ...
  • # 使用PySpark ## 配置python環境 在所有節點上按照python3,版本必須是python3.6及以上版本 ```Shell yum install -y python3 ``` 修改所有節點的環境變數 ```Shell export JAVA_HOME=/usr/local/jdk ...
  • 1、查找mongodb相關鏡像 docker search mongo 找到相關的鏡像進行拉取,如果不指定版本,預設下載最新的mongoDB。建議自己先查找需要那個版本後在進行拉取,因為mongoDB不同版本之間差距較大。 2、拉取鏡像 這裡拉取mongodb6.0 docker pull mong ...
  • 這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 界面無滾動條 滾動條的優化也有很多種,比如隨便再網上搜索美化瀏覽器滾動條樣式,就會出現些用css去美化滾動條的方案。 那種更好呢? 沒有更好只有更合適 像預設的滾動條的話,他能讓你方便摁著往下滑動(他比較寬)特別省勁,不用擔心美化過後變細 ...
  • # vane 寫這個的初衷是因為每次用node寫介面的時候總是需要一些寫大一堆的東西, 也有些人把很多介面都放在一個js文件內, 看起來很是雜亂, 後來用到nuxt寫的時候, 感覺用文件名來命名介面路徑很是方便, 無論是query參數還是params參數,都可以通過文件名來命名, 也可以通過文件夾層 ...
  • * 環境變數問題 ```typescript datasource db { provider = "mysql" url = env("DATABASE_URL") } ``` 1. `npx prisma db push` 預設取 .env 配置文件,那多環境怎麼處理? 2. 增加 `.env. ...
  • # 什麼是巡檢報告 巡檢報告是指對某一個系統或設備進行全面檢查,並把檢查結果及建議整理成報告的過程。 巡檢報告通常用於評估系統或設備的運行狀況與性能,以發現問題、優化系統、提高效率、降低故障率等方面提供參考。 ![file](https://img2023.cnblogs.com/other/233 ...
  • 前言 現在很多網頁用的都是固定標題欄,就像這樣: 很多網站為了相容小視窗還會做個JS適配: 但是如果視窗比這還小的話... 那就只剩下一部分了。 由於設置position:fixed後元素不會隨著滾動條滾動,所以超出頁面邊緣的部分將永遠看不見,除非增大視窗或縮小顯示比例。 很多設計師忘記考慮這一點了 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...