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

Vue3實現(xiàn)組件級基類的多種方法

 更新時間:2023年04月28日 08:37:15   作者:金色海洋(jyk)  
vue3提供了 mixins和extends,但是嘗試之后發(fā)現(xiàn)這兩種方法只支持純OptionAPI,設置的data會被識別,但是設置的setup里return 的 reactive,完全無效,setup也沒有被執(zhí)行,這篇文章主要介紹了Vue3實現(xiàn)組件級基類的幾種方法,需要的朋友可以參考下

Vue3的組件有三種代碼組織方式

  • 純Option API (不含setup)
  • option API + setup
  • 純 setup (即composition API)

對于這三種形式,設置基類的方法也略有不同。

使用 mixins、extends

vue3提供了 mixins和extends,但是嘗試之后發(fā)現(xiàn)這兩種方法只支持純OptionAPI,設置的data會被識別,但是設置的setup里return 的 reactive,完全無效,setup也沒有被執(zhí)行。
所以這種方式只能使用于第一種方式。

使用 hooks (function、class)

既然官方?jīng)]有提供,那么我們自己來想想辦法。我們先觀察一下組件的代碼(第二種情況):

<template>
  <!--模板-->
  舉例
</template>
<script lang="ts">
  import { defineComponent } from 'vue'
  export default defineComponent({
    name: 'ui-core-',
    components: {
      // 注冊共用組件
    },
    props: {
      // 定義共用屬性
    },
    setup(props, context) {
      // 各種共用操作
      _logger()
      _setTitle()
      // 共用成員
      const foo = reactive ({})
      return {
        foo
      }
    }
  })
</script>

defineComponent 方法接收一個對象,對象需要有特定的幾個屬性,比如name、components、props、setup等。
那么也就是說,我們可以做一個函數(shù)返回這樣的對象即可。
比如我們先建立一個js(或則ts)文件:

export function base (name, callback) {
  return {
    name: 'ui-' + name,
    components: {
      // 注冊共用組件
    },
    props: {
      // 定義共用屬性
    },
    setup(props, context) {
      // 各種共用操作
      _logger()
      _setTitle()
      // 共用成員
      const foo = reactive ({})
      // 執(zhí)行其他操作
      const re = callback(props, context)
      return {
        foo,
        ...re
      }
    }
  }
}

有點像模板模式。

傳入name和一個回調函數(shù),props, context作為參數(shù)進行傳遞。內(nèi)部成員也可以作為參數(shù)傳遞。
這樣一個簡單的基類就做成了,如果你覺得function不好看,那么可以換成class。

export default class BaseComponent {
  name: string
  components: any
  props: any
  setup: any
  constructor (name: string, callback: (props: any, context: any) => any) {
    this.name = name
    this.components = {}
    this.props = {}
    this.setup = (props: any, context: any) => {
      // 各種共用操作
      _logger()
      _setTitle()
      // 執(zhí)行其他操作
      const re = callback(props, context)
      return {
        ...re
      }
    }
  }
}

有了class之后,還可以設置子類,不過感覺有點繁瑣??傊?,反正可以實現(xiàn)就對了。

script setup怎么辦

上述這種方法應該也是可以支持純composition API的,但是有點小問題,defineProps 和 defineEmits 并不是普通 js 函數(shù),而是一種“宏”。
引用官網(wǎng)的解釋:

defineProps 和 defineEmits 都是只能在 <script setup> 中使用的編譯器宏。他們不需要導入,且會隨著 <script setup> 的處理過程一同被編譯掉。
也就是說 defineXXX系列 只有在 <script setup> 標簽內(nèi)部才會被識別,如果在單獨的js文件里面,不會被識別。

這就導致 defineProps 和 defineEmits 無法做成基類的形式。
如果需要的基類不涉及 defineProps 和 defineEmits 的話,那么還是可以在單獨的js文件里面定義一個function或者class的,(即做一個綜合的hooks)。

如果涉及 defineProps 和 defineEmits,那么,我也沒想出來辦法。(只能第二種方式)

到此這篇關于Vue3實現(xiàn)組件級基類的幾種方法的文章就介紹到這了,更多相關Vue3組件級基類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論