SWATCAT
SWATCAT

Reputation: 1

How do I refer to custom Javascript file in my Vuepress project so the JS functions are globally available?

I am working on a Vuepress project which was setup by a former colleague. I am trying to refer my custom Javascript file in a root component so that it is globally available. I don't want to refer to it in every component, because that would be redundant and it does not work as expected.

I read enhanceApp.js is the way to go so I tried attaching the JS file to Vue Object but it does not work. Any help is appreciated!

This is enhanceApp.js

import HelpersPlugin from '../../src/js/helpers';
export default ({
 Vue,
 options,
 router, // the router instance for the app
 siteData // site metadata
}) => {
Vue.use(HelpersPlugin);
}

this is src/js/helpers folder which contains, accordion.js (My custom JS file) and index.js

index.js:

import AccordionHelper from './accordion';
export default { 
install: (Vue, options) => {
  Vue.prototype.$helpers = {
   accordion: AccordionHelper
  }
 }
}

accordion.js: (has plain JS with DOM manipulation functions)

export default () => {
    console.log("Hello");
    //DOM manipulation JS
}

This is the folder structure:

docs
    -> .vuepress
        - components
            * Accordion.vue
            * Buttons.vue
        - theme
            * Layout.vue
            * SearchBox.vue
        - config.js
        - enhanceApp.js
    -> accordion
        - README.md
    -> buttons
        - README.md
src
    -> js
        - helpers
            * accordion.js
            * index.js

I am looking to use accordion.js in both Accordion.vue and Layout.vue without having to refer it in both components.

Upvotes: 0

Views: 1722

Answers (1)

Robert
Robert

Reputation: 1907

I believe this is the recommended way of sharing common JS functions. Found this by ejecting the default theme from Vuepress.

.vue File:

<template>
  <div v-if="canHelp()">Help is on the way</div>
</template>

<script>
import { canHelp } from './helpers'
export default {
  methods: {
    canHelp
  }
}
</script>

helpers.js

export function canHelp () {
    return true
}

Upvotes: 1

Related Questions