欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺聊一下Vue2中的functional組件

 更新時間:2023年08月15日 09:07:27   作者:陽樹陽樹  
最近聽到有人提到了Vue2的functional組件,大致上是說這個東西沒有生命周期,在渲染層面上,會減少很多的消耗,一番處理之后,首屏時間和內存都能減少不少,所以本文小編就來和大家聊聊Vue2中的functional組件<BR>

前言

最近組內有一個分享提到了 Vue2 的 functional 組件,大致上是說這個東西沒有生命周期,在渲染層面上,會減少很多的消耗,一番處理之后,首屏時間和內存都能減少不少。

由此,我打算來好好學一下挖一下這個知識點。

functional 組件是什么?

Vue.js 中的 functional 函數(shù)化組件是一種特殊類型的無狀態(tài)組件,它不依賴于內部狀態(tài),只依賴于傳入的 props。這種組件沒有實例,也就是說它們沒有 this 上下文。函數(shù)化組件的主要特點如下:

  • 無狀態(tài):函數(shù)化組件不包含響應式數(shù)據(jù)或內部狀態(tài),它們只依賴于傳入的 props。
  • 無實例:函數(shù)化組件沒有實例,因此沒有 this 上下文。
  • 更高的性能:由于沒有實例和響應式數(shù)據(jù),函數(shù)化組件的渲染性能更高,適用于頻繁更新的場景。
  • 簡潔的定義:函數(shù)化組件使用 render 函數(shù)定義,不需要完整的 Vue 組件選項對象。

函數(shù)化組件的定義示例:

Vue.component('my-functional-component', {
  functional: true,
  props: {
    message: {
      type: String,
      required: true
    }
  },
  render: function (createElement, context) {
    return createElement('div', context.props.message);
  }
});

functional函數(shù)化組件做比對是深度比對,會對對象深入的做對比,不是淺比較:

如果 props 對象外部不變,但內部的參數(shù)發(fā)生變化,函數(shù)化組件會重新渲染。因為函數(shù)化組件是無狀態(tài)的,它們只依賴于傳入的 props。當 props 的內部參數(shù)發(fā)生變化時,Vue 會檢測到這些變化并重新渲染函數(shù)化組件。

Vue.component('my-functional-component', {
  functional: true,
  props: {
    userInfo: {
      type: Object,
      required: true
    }
  },
  render: function (createElement, context) {
    return createElement('div', context.props.userInfo.name);
  }
});

特點

1.functional 函數(shù)化組件本身無 watch/computed,這就導致我們不能像在普通 Vue 組件中那樣使用 watch 或 computed 屬性來監(jiān)聽參數(shù)變化。因為函數(shù)化組件沒有實例和響應式數(shù)據(jù),它們只依賴于傳入的 props。當 props 發(fā)生變化時,函數(shù)化組件會自動重新渲染。

如果我們想要監(jiān)聽怎么辦?

比較可行的辦法是:在父組件中監(jiān)聽 props 變化,并在適當?shù)臅r機傳遞新的 props 給函數(shù)化組件。這樣,函數(shù)化組件會在接收到新的 props 時自動重新渲染。

2.functional 函數(shù)化組件本身無實例,這會導致如下后果:

  • 在函數(shù)化組件中,無法使用 this 訪問組件實例,因為它們沒有實例。
  • 由于沒有實例,函數(shù)化組件無法使用 Vue 實例的方法和屬性,例如 $emit、$watch、$refs 等。
  • 函數(shù)化組件沒有實例,因此無法使用生命周期鉤子函數(shù),如 created、mounted、updated 等。
  • 函數(shù)化組件沒有響應式數(shù)據(jù)和內部狀態(tài),它們只依賴于傳入的 props。這意味著我們無法在函數(shù)化組件中使用 data、computed 和 watch 等選項。
  • 在函數(shù)化組件中,我們需要通過 context 對象訪問插槽(slots)和作用域插槽(scoped slots),而不是使用 this.$slots 和 this.$scopedSlots。

使用如下:

Vue.component('my-functional-component', {
  functional: true,
  props: {
    message: {
      type: String,
      required: true
    }
  },
  render: function (createElement, context) {
    // 訪問 props
    const message = context.props.message;
    // 訪問插槽
    const slots = context.slots();
    const defaultSlot = slots.default;
    // 訪問作用域插槽
    const scopedSlots = context.scopedSlots;
    const customSlot = scopedSlots.customSlot;
    // 訪問事件監(jiān)聽器
    const listeners = context.listeners;
    const clickListener = listeners.click;
});

到此這篇關于淺聊一下Vue2中的functional組件的文章就介紹到這了,更多相關Vue2 functional組件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論