Nuxt.js【Vue.js】でシェアボタン(ページ共有)を実装する方法になります。
Nuxt.js【Vue.js】でシェアボタン(ページ共有)を実装する方法
<template>
<div class="share_buttons">
<button v-if="isNavigatorShareButton" @click="navigatorShare">
<font-awesome-icon icon="share-alt" />
</button>
<button v-if="!isNavigatorShareButton" @click="twitterShare">
<font-awesome-icon :icon="['fab', 'twitter']" />
</button>
<button v-if="!isNavigatorShareButton" @click="facebookShare">
<font-awesome-icon :icon="['fab', 'facebook']" />
</button>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
data() {
return {
isNavigatorShareButton: true,
title: 'タイトル',
text: 'テキストが入ります',
url: 'https://demo.jp/demo'
}
},
mounted() {
if (navigator.share === undefined) {
this.isNavigatorShareButton = false
}
},
methods: {
// Web Share APIが使える場合
navigatorShare() {
if (navigator.share) {
navigator.share({
title: this.title,
text: this.title + '\n' + this.text,
url: this.url
})
}
},
// Twitter
twitterShare() {
const baseUrl = 'https://twitter.com/intent/tweet?'
const text = ['text', this.title + '\n' + this.text]
const url = ['url', this.url]
const parameter = new URLSearchParams([text, url]).toString()
const shareUrl = `${baseUrl}${parameter}`
window.open(shareUrl, 'twitter', 'top=200,left=300,width=600,height=400')
},
// Facebook
facebookShare() {
const baseUrl = 'https://www.facebook.com/sharer/sharer.php?'
const url = ['u', this.url]
const parameter = new URLSearchParams([url]).toString()
const shareUrl = `${baseUrl}${parameter}`
window.open(shareUrl, 'facebook', 'top=200,left=300,width=600,height=400')
}
}
})
</script>
シェアボタンについては、Font Awesomeを使用しています。
解説
Web Share APIが使える場合
共有に便利なWeb Share APIが使える場合はそちらを利用します。
if (navigator.share) {
navigator.share({
title: this.title,
text: this.title + '\n' + this.text,
url: this.url
})
navigator.share
は、title、text、urlの3つのオプションを設定することができます。
ボタンについては、mounted
でWeb Share APIが使えるかを判定して、表示を切り替えています。
mounted() {
if (navigator.share === undefined) {
this.isNavigatorShareButton = false
}
}
Web Share APIが使えない場合
Web Share APIが使えない場合は、TwitterとFacebookのシェアボタンを設置しています。
window.open()
でリンク先を別タブで開くようにしています。
twitterShare() {
const baseUrl = 'https://twitter.com/intent/tweet?'
const text = ['text', this.title + '\n' + this.text]
const url = ['url', this.url]
const parameter = new URLSearchParams([text, url]).toString()
const shareUrl = `${baseUrl}${parameter}`
window.open(shareUrl, 'twitter', 'top=200,left=300,width=600,height=400')
}
faceBookShare() {
const baseUrl = 'https://www.facebook.com/sharer/sharer.php?'
const url = ['u', this.url]
const parameter = new URLSearchParams([url]).toString()
const shareUrl = `${baseUrl}${parameter}`
window.open(shareUrl, 'facebook', 'top=200,left=300,width=600,height=400')
}