motorscript.com

ShareThis component for Vue.js/Nuxt.js

Published:
ShareThis provides javascript embed code for HTML which doesn't work directly for Single Page Applications like the one created with Vue.js/Nuxt.js. Re-initializing ShareThis on page mount will fix it for Vue.js apps.

The Component: ShareThis.vue

<template>
  <div class="share-this">
    <!-- This is the placement code ShareThis provides. -->
    <div class="sharethis-inline-share-buttons"></div>
  </div>
</template>

<script>
export default {
  mounted() {
    const st = window.__sharethis__
    if (!st) {
      const script = document.createElement('script')
      script.src =
        'https://platform-api.sharethis.com/js/sharethis.js#property=[property_id]>&product=sop'
      document.body.appendChild(script)
    } else if (typeof st.initialize === 'function') {
      st.href = window.location.href
      st.initialize()
    }
  }
}
</script>

<style scoped>
.share-this {
  margin-bottom: 0.5em;
}
</style>

Please make sure you use the correct property id in the sharethis js url for src attribute of the appended script tag. You can get the property id from the code ShareThis dashboard provides you.

If you are using something other than the inline share buttons, update the placement code on the <template> section.

What the component does:

If the browser window hasn't loaded the ShareThis javascript yet, the script is loaded. If it is already available, it is re-initialized with the current URL.

Usage

<template>
  <div class="container">
    <ShareThis />
    <div class="other-content"></div>
  </div>
</template>

<script>
import ShareThis from '~/components/ShareThis'

export default {
  components: { ShareThis }
}
</script>

The URL needs not be passed as ShareThis initialization code uses the current browser URL.