/ Gists / Use Global Utility Methods For DRYer Code
On gists

Use Global Utility Methods For DRYer Code

Vue.js

utils.js Raw #

// import store from '../store' <-- To access your Vuex store
import Vue from 'vue' // <-- used for vue-toastification

class Utils {
  // Copy a string to user's clipboard
  copyToClipboard(text) {
    let copyText = document.createElement('input')
    document.body.appendChild(copyText)
    copyText.value = text
    copyText.select()
    document.execCommand('copy')
    document.body.removeChild(copyText)

    // Show toast on copy success
    // (using the vue-toastification package here)
    Vue.$toast.success('Copied address to clipboard: ' + text, {
      position: 'top-right',
      timeout: 3000
    })
  }
}

export default new Utils()

app.js Raw #

// Utils
import Utils from './utils/utils.js'   // <-- import file
const app = createApp(App)
 // Init Global Utils
 app.config.globalProperties.$utils = Utils   // <-- set globally
app.mount('#app')

component.vue Raw #

// In template
$utils.copyToClipboard(text)
// In methods
this.$utils.copyToClipboard(text)