1. 程式人生 > 程式設計 >淺談Vue 函式式元件的使用技巧

淺談Vue 函式式元件的使用技巧

什麼是函式式元件

沒有管理任何狀態,也沒有監聽任何傳遞給它的狀態,也沒有生命週期方法,它只是一個接受一些 prop 的函式。簡單來說是 一個無狀態和無例項的元件

基本寫法:

Vue.component('my-component',{
 functional: true,// Props 是可選的
 props: {
  // ...
 },// 為了彌補缺少的例項
 // 提供第二個引數作為上下文
 render: function(createElement,context) {
  // ...
 }
})

.vue 單檔案元件寫法

<template functional>
 ...
</template>

因為函式式元件沒有 this,引數就是靠 context 來傳遞的了,有如下欄位的物件:

  • props:提供所有 prop 的物件
  • children:VNode 子節點的陣列
  • slots:一個函式,返回了包含所有插槽的物件
  • scopedSlots:(2.6.0+) 一個暴露傳入的作用域插槽的物件。也以函式形式暴露普通插槽。
  • data:傳遞給元件的整個資料物件,作為 createElement 的第二個引數傳入元件
  • parent:對父元件的引用
  • listeners:(2.3.0+) 一個包含了所有父元件為當前元件註冊的事件監聽器的物件。這是 data.on 的一個別名。
  • injections:(2.3.0+) 如果使用了 inject 選項,則該物件包含了應當被注入的 property。

使用技巧

以下總結、都是基於使用 <template> 標籤開發函式式元件中遇到的問題

attr 與 listener 使用

平時我們在開發元件時,傳遞 prop 屬性以及事件等操作,都會使用v-bind="$attrs"和 v-on="$listeners"。而在函式式元件的寫法有所不同,attrs屬性整合在 data中。

<template functional>
 <div v-bind="data.attrs" v-on="listeners">
  <h1>{{ props.title }}</h1>
 </div>
</template>

class 與 style 繫結

在引入函式式元件、直接繫結外層的class類名和style樣式是無效的。data.class 表示動態繫結class,data.staticClass 則表示繫結靜態class,data.staticClass 則是繫結內聯樣式
TitleView.vue

<template functional>
 <div :class="[data.class,data.staticClass]" :style="data.staticStyle">
  <h1>{{ props.title }}</h1>
 </div>
</template>

Test.vue

<template>
 <title-view
  :class="{title-active: isActive}"
  style="{ color: red }"
  title="Hello Do"
 />
</template>

component 元件引入

函式式元件引入其他元件方式如下,具體參考:github.com/vuejs/vue/i…

<template functional>
 <div class="tv-button-cell">
  <component :is="injections.components.TvButton" type="info" />
  {{ props.title }}
  </component>
 </div>
</template>

<script>
import TvButton from '../TvButton'

export default {
 inject: {
  components: {
   default: {
    TvButton
   }
  }
 }
}
</script>

$options 計算屬性

有時候需要修改prop資料來源,使用 Vue 提供的 $options 屬性,可以訪問這個特殊的方法。

<template functional>
 <div v-bind="data.attrs" v-on="listeners">
  <h1>{{ $options.upadteName(props.title) }}</h1>
 </div>
</template>

<script>
 export default {
  updateName(val) {
   return 'hello' + val
  }
 }
</script>

總結

雖然速度和效能方面是函式式元件的優勢、但不等於就可以濫用,所以還需要根據實際情況選擇和權衡。比如在一些展示元件。例如, buttons, tags,cards,或者頁面是靜態文字,就很適合使用函式式元件。

到此這篇關於淺談Vue 函式式元件的使用技巧的文章就介紹到這了,更多相關Vue 函式式元件內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!