@@ -13,6 +13,7 @@ export default {
1313 this . $ssrContext . title = this . $title
1414 this . $ssrContext . lang = this . $lang
1515 this . $ssrContext . pageMeta = renderPageMeta ( mergedMetaItems )
16+ this . $ssrContext . canonicalLink = renderCanonicalLink ( this . $canonicalUrl )
1617 }
1718 } ,
1819 // Other life cycles will only be called at client
@@ -22,6 +23,7 @@ export default {
2223
2324 // update title / meta tags
2425 this . updateMeta ( )
26+ this . updateCanonicalLink ( )
2527 } ,
2628
2729 methods : {
@@ -39,18 +41,45 @@ export default {
3941 // description needs special attention as it has too many entries
4042 return unionBy ( [ { name : 'description' , content : this . $description } ] ,
4143 pageMeta , this . siteMeta , metaIdentifier )
44+ } ,
45+
46+ updateCanonicalLink ( ) {
47+ removeCanonicalLink ( )
48+
49+ if ( ! this . $canonicalUrl ) {
50+ return
51+ }
52+
53+ document . head . insertAdjacentHTML ( 'beforeend' , renderCanonicalLink ( this . $canonicalUrl ) )
4254 }
4355 } ,
4456
4557 watch : {
4658 $page ( ) {
4759 this . updateMeta ( )
60+ this . updateCanonicalLink ( )
4861 }
4962 } ,
5063
5164 beforeDestroy ( ) {
5265 updateMetaTags ( null , this . currentMetaTags )
66+ removeCanonicalLink ( )
67+ }
68+ }
69+
70+ function removeCanonicalLink ( ) {
71+ const canonicalEl = document . querySelector ( "link[rel='canonical']" )
72+
73+ if ( canonicalEl ) {
74+ canonicalEl . remove ( )
75+ }
76+ }
77+
78+ function renderCanonicalLink ( link = '' ) {
79+ if ( ! link ) {
80+ return ''
5381 }
82+ return `<link href="${ link } " rel="canonical" />`
5483}
5584
5685/**
0 commit comments