如何在Nuxt3使用vue-social-sharing套件

前言

vue-social-sharing是用來透過社群軟體分享網頁內容的一個套件,例如:Facebook、Line 社群軟體,在npm有高手寫了一個vue-social-sharing套件,在Vue和Nuxt2可以成功用說明成功安裝並使用,但在Nuxt3會引入失敗,所以這一篇文章就來實現如何在Nuxt3將此套件引入並實作相關邏輯出來。

作法

  1. 先進行套件安裝 npm install — save vue-social-sharing@next

  2. 嘗試依據npm作者提供之方式引入,在nuxt.config.ts檔案內寫上modules屬性內寫入套件名。

    1
    2
    3
    4
    5
    export default defineNuxtConfig({
    modules: [
    'vue-social-sharing/nuxt'
    ]
    })

    但無法順利引用,判斷套件可使用在Nuxt2,無法使用在Nuxt3

  3. 解決方法:使用plungins方式引用此套件

    (1)於plugins內新增socialSharing.js檔案,內容如下

    1
    2
    3
    4
    5
    import VueSocialSharing from "vue-social-sharing";

    export default defineNuxtPlugin(nuxtApp => {
    nuxtApp.vueApp.use(VueSocialSharing);
    });

    (2)在components資料夾內新增SocialShare.vue檔,內容如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <script>
    const sharing = ref({
    url: "https://github.com/nicolasbeauvais/vue-social-sharing?ref=morioh.com&utm_source=morioh.com",
    title: "Say hi to Vite! A brand new, extremely fast development setup for Vue.",
    description: 'This week, I’d like to introduce you to "Vite", which means "Fast". It’s a brand new development setup created by Evan You.',
    quote: "The hot reload is so fast it's near instant. - Evan You",
    hashtags: "vuejs,vite,javascript",
    });
    const networks = reactive([
    { network: "facebook", name: "Facebook", icon: "fab fah fa-lg fa-facebook-f", color: "#1877f2" },
    { network: "line", name: "Line", icon: "fab fah fa-lg fa-line", color: "#00c300" },
    ]);
    </script>

    <template>
    <ShareNetwork class="float-right" v-for="network in networks" :network="network.network" :key="network.network"
    :style="{ backgroundColor: network.color }" :url="sharing.url" :title="sharing.title"
    :description="sharing.description" :quote="sharing.quote" :hashtags="sharing.hashtags"
    :twitterUser="sharing.twitterUser">
    <i :class="network.icon"></i>
    <span>{{ network.name }}</span>
    </ShareNetwork>
    </template>

    (3) 如有多個分享社群,因Nuxt server render問題,會發生只有第一個社群媒體圖示會正常呈現出來,則引入上述步驟時的component時應使用defineAsyncComponent非同步引入方式,script標籤內容如下

    1
    const SocialShare = defineAsyncComponent(() => import("../components/SocialShare.vue"));

    並在template使用ClientOnly方式,讓該component只在client端render出來,內容如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <ClientOnly>
    <div>
    <Suspense>
    <template #default>
    <SocialShare />
    </template>
    <template #fallback>
    <p>Loading...</p>
    </template>
    </Suspense>
    </div>
    </ClientOnly>

    (4) 成功引入!