Vue.jsでアプリを作っており、投稿記事ごとに異なるOGP画像やタイトルを設定したいと思っています。
index.htmlのhead内でmetaを設定しており、/post/:idというURLに行った場合のみ動的にその記事のタイトルやサムネイル画像に設定したいのですが、以下のソースでは上手く動作しませんでした。
現状ではブラウザのタブなどに表示されるページタイトルは変わっており、シェア画面へも飛べるのですが、OGP画像などがindex.htmlに記載したもののまま書き換わりません。
どのように直せばいいかご教授頂きたいです。
index
1<head> 2 <!-- OGP画像設定 --> 3 <!-- ※基本共通設定 --> 4 <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#"> 5 <title>サンプルアプリ</title> 6 <meta property="og:title" content="サンプルアプリ" /> 7 <meta property="og:type" content="website" /> 8 <meta property="og:url" content="https://sample.com/" /> 9 <meta property="og:image" content="https://sample.com/img/ogp.png" /> 10 <meta property="og:site_name" content="サンプルアプリ" /> 11 <meta property="og:description" content="これはサンプルです。" /> 12 13 <!-- Facebook用設定 --> 14 <meta property="fb:app_id" content="001122334455667" /> 15 16 <!-- ※ Twitter共通設定 --> 17 <meta name="twitter:image" content="https://sample.com/img/ogp.png" /> 18 <meta name="twitter:card" content="summary_large_image" /> 19 <meta name="twitter:site" content="@sample" /> 20</head>
Vue
1<script> 2 export default{ 3 4 data(){ 5 return{ 6 fbUrl: '', 7 twUrl: '', 8 } 9 }, 10 11 mounted(){ 12 this.createSnsUrl(); 13 }, 14 15 methods: { 16 17 createSnsUrl (){ 18 // ページタイトル・説明を設定 19 document.title = this.post.title; 20 document.querySelector("meta[name='description']").setAttribute('content', this.post.content); 21 22 // 現在のurlをエンコード 23 var url = encodeURIComponent(location.href); 24 25 document.querySelector("meta[property='og:type']").setAttribute('content', 'article'); 26 document.querySelector("meta[property='og:title']").setAttribute('content', this.post.title); 27 document.querySelector("meta[property='og:url']").setAttribute('content', url); 28 document.querySelector("meta[property='og:image']").setAttribute('content', this.post.image); //this.post.imageはサムネイル画像への絶対パス 29 document.querySelector("meta[name='twitter:image']").setAttribute('content', this.post.image); //this.post.imageはサムネイル画像への絶対パス 30 31 // ページ文言 32 var txt = encodeURIComponent(document.querySelector("meta[property='og:title']").getAttribute('content')) + 'をシェア'; 33 34 // Facebook用のurl作成 35 this.fbUrl = 'https://www.facebook.com/sharer/sharer.php?u=' + url; 36 37 // Twitter用のurl作成 38 this.twUrl = 'https://twitter.com/intent/tweet?text=' + txt + '&url=' + url; 39 }, 40 } 41</script> 42
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/06 08:07