乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      Vue3.x 從零開始(二)—— 重新認(rèn)識 Vue 組件

       小樣樣樣樣樣樣 2021-09-15

      Vue 3 更新了許多組件中的語法,包括生命周期、filter、setup、teleport 等

      為了介紹這些特性,需要先了解一下 Vue 組件的基本玩法

      這篇文章介紹的內(nèi)容基本都是沿用 Vue 2 的語法,只在一些細(xì)節(jié)上有所調(diào)整

       

      一、單文件組件

      通過 Vue.createApp() 創(chuàng)建的應(yīng)用,可以使用 component 方法創(chuàng)建自定義組件

      const app = Vue.createApp({});
      app.component('my-component', {
        data() {
          return {
            name: 'Wise.Wrong'
          }
        },
        template: `<div>hello {{name}}</div>`,
      });

      不過在實(shí)際項(xiàng)目中,都是使用“單文件組件”,也就是以 .vue 文件的形式開發(fā)

      比如上面組件,改寫成單文件組件就是這樣的:

      <template>
        <div>hello {{ name }}</div>
      </template>
      
      <script lang="ts">
      /* 當(dāng)前文件路徑: src/components/my-component.vue */
      import { defineComponent } from 'vue';
      export
      default defineComponent({ name: 'MyComponent', data() { return { name: 'Wise.Wrong', }; }, }); </script>

      這里的 data 必須通過函數(shù)的形式返回一個(gè)對象,而不能直接使用對象

      // 2.x 可以接收對象,但 3.x 的 data 只能是 function 

       

      假如現(xiàn)在還有另一個(gè)組件 <home> ,我們希望在 <home> 組件中使用 <my-component>

      可以直接在 <home> 中引入 my-component.vue 文件,然后通過 components 屬性注冊組件

      上面的代碼中,我在 components 中使用的是大駝峰命名組件,而在 <template> 中使用的是短線命名

      這是因?yàn)?HTML 本身不區(qū)分大小寫,Vue 更建議我們在 DOM 中使用全小寫的短線命名的方式

       

      二、Props

      現(xiàn)在我們有了一個(gè)父組件 <home> 與子組件 <my-component>

      如果我想在父組件中向子組件傳遞參數(shù),可以通過 Props

      首先在子組件定義 props

      然后父組件傳入對應(yīng)的 props 屬性值

      最終結(jié)果

      除了定義數(shù)組形式的 props 之外,還可以使用對象類型,這樣就能對 props 做更多限制

      export default defineComponent({
        // ...
        props: {
          likes: String, // 僅限定類型
          years: {
            type: [String, Number],
            required: true, // 必填
          },
          info: {
            type: Object,
            default: () => ({ // 對象和數(shù)組類型的默認(rèn)值只能用函數(shù)返回
              title: '這里是對象類型的 prop',
            }),
          },
          type: {
            // 自定義校驗(yàn)函數(shù)
            validator: (val: string) => (
              ['success', 'warning', 'danger'].indexOf(val) !== -1
            ),
          },
        },
        // ...
      });

      如果父組件傳參不符合子組件中 props 定義的規(guī)則,Vue 會在控制臺拋錯(cuò)

      更多關(guān)于 Props 的使用可以查看官方文檔

       

      三、無狀態(tài)組件

      在子組件中,props 和 data 一樣都是直接掛載到 this 對象下的,可以通過 this.xxx 的方式取值

      對于某些功能型組件,只需要 props 不需要 data。比如這樣的一個(gè)提示框組件:

      <template>
        <div :class="['alert', type]">
          <div class="alert-content">{{content}}</div>
        </div>
      </template>
      
      <script lang="ts">
      import { defineComponent } from 'vue';
      
      export default defineComponent({
        name: 'Alert',
        props: ['type', 'content'],
      });
      </script>

      這種只接收 props,沒有定義 data、methods、computed 等響應(yīng)數(shù)據(jù)的組件,被稱為無狀態(tài)組件

      在 Vue 2 中,無狀態(tài)組件的初始化比普通組件快得多,所以經(jīng)常會作為性能優(yōu)化的一個(gè)考量

      為了創(chuàng)建一個(gè)無狀態(tài)組件,必須在 <template> 中聲明 functional

      <template functional>
      Vue 2
      </template>

      但是在 Vue 3 中,無狀態(tài)組件不再需要聲明 functional

      只需要像一個(gè)普通組件一樣定義,只是不要添加 data 等響應(yīng)數(shù)據(jù),就像上面的提示框組件那樣

      官方文檔是這樣解釋的:

      However, in Vue 3, the performance of stateful components has improved to the point that the difference is negligible.

      但是,在Vue 3中,有狀態(tài)組件的性能已提高到比肩無狀態(tài)組件的程度。

      emmmmmm... 相當(dāng)?shù)呐蛎?..

      不過我喜歡~

       

      四、Mixin

      與無狀態(tài)組件相對應(yīng)的是有狀態(tài)組件,也就是帶有 data 等響應(yīng)數(shù)據(jù)的組件,我們工作中寫的組件大部分都是有狀態(tài)組件

      而隨著業(yè)務(wù)的不斷擴(kuò)大,整個(gè)應(yīng)用變得非常臃腫,這時(shí)候組件共用和邏輯抽取就尤為重要,這時(shí)候可以使用 mixin

       

      假如我們有三個(gè)組件,它們的 js 部分都包含以下內(nèi)容:

      <script>
      export default {
        // ...
        data() {
          return {
            // ...
            company: {
              name: 'Perfect World',
              address: 'Chongqing China',
            },
            loading: false,
          }
        },
        props: {
          // ...
          title: String
        },
        methods: {
          // ...
          fetchCompanyInfo(data) {
            this.loading = true;
            return fetch('/api')
              .then(res => res.json())
              .then(res => {
                this.company = { ...res.data };
              })
              .finally(_ => { 
                this.loading = false;
              })
          }
        },
      };
      </script>

      三個(gè)組件都包含響應(yīng)數(shù)據(jù)(data) loading 和 company,以及相應(yīng)的查詢方法(methods) fetchInfo,還有一個(gè)來自父組件的參數(shù)(props) title

      這些邏輯完全一樣,如果要在三個(gè)組件中各寫一份完全一樣的代碼,就會非常難受,不利于維護(hù)

      有了 mixin 之后,我們就能把這些邏輯寫在一個(gè)對象里面并導(dǎo)出

      /* mixin-test.js */
      export default {
        data: () => ({
          loading: false
        }),
        props: {
          title: String
        },
        methods: {
          fetchCompanyInfo(data) {
            // ...
          }
        }
      }

      然后在需要用到這部分邏輯的組件中引入,并注冊到 mixins

      mixins 接收的是一個(gè)數(shù)組,也就是說可以同時(shí)注冊多個(gè) mixin

      <script>
      import MixinTest from "./mixin/mixin-test.js";
      
      export default {
        // ...
        mixins: [ MixinTest ],
      };
      </script>

      Vue 在初始化組件的時(shí)候,會將引入的 mixin 對象和當(dāng)前組件進(jìn)行合并

      在合并的時(shí)候如果遇到了同名選項(xiàng),對于不同的類型 (data、props、methods) 會有不同的策略

      1. 如果是 props、methods、components、directives 沖突,會以組件本身的鍵值對覆蓋 mixin

      2. 對于生命周期這樣的鉤子函數(shù)出現(xiàn)沖突,會先觸發(fā) mixin 中的鉤子函數(shù),然后觸發(fā)組件中的鉤子函數(shù)

      3. 如果 data 發(fā)生沖突,將執(zhí)行淺層次的合并:

      const Mixin = {
        data: ()=> ({
          user: { name: 'Jack', id: 1 }
        })
      }
      
      const Comp = {
        mixins: [Mixin],
        data: () => ({
          user: { id: 2 }
        })
      }
      
      // 最終的結(jié)果是:
      {
        user: { id: 2 }
      }

      而在 Vue 2 中,data 會執(zhí)行深層次的合并,上例的結(jié)果會變成:

      {
        user: { id: 2, name: 'Jack' }
      }

      在 Vue 2 的時(shí)代,Mixin 是封裝的共用邏輯的常用手段,但這種方式一直都受到很多開發(fā)者的質(zhì)疑

      首先就是 mixin 的重名問題,雖然 Vue 有一套合并策略(這個(gè)合并策略可以自定義)來處理 mixin 的重名問題

      但組件內(nèi)部是無法知道 mixin 到底提供了哪些字段,如果后來的維護(hù)人員不熟悉組件中的 mixin,在維護(hù)代碼的時(shí)候很容易因?yàn)橹孛膯栴}導(dǎo)致 bug

      而且 mixin 可以使用組件中的數(shù)據(jù),如果維護(hù)組件的時(shí)候更改了 mixin 所依賴的數(shù)據(jù),也會導(dǎo)致 bug

      為了解決這些問題,Vue 3 推出了 Composition API ,用函數(shù)式編程的思想來封裝組件邏輯

      欲知 Composition API 如何,請聽下回分解~

       

        本站是提供個(gè)人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多