jeremihza's avatar

how do you include the code or script in nuxt js with the script tags

<script>
        $(document).ready(function () {
            /* This is basic - uses default settings */

            $("a.single_image").fancybox();

            /* Using custom settings */

            $("a#inline").fancybox({
                hideOnContentClick: true,
            });
        });
    </script>```
0 likes
1 reply
rodrigo.pedra's avatar

As nuxt.js treats each page as a Vue component, you can't add a script tag to a Vue template.

Also, even if you could, navigating through a SPA, would not trigger the DOMContentLoaded event jQuery needs to call the $(document).ready(...) function on each page navigation. Your nuxt app is loaded once in the browser.

What you need is to integrate this external component with Vue. Vue docs has an example on how to do this:

https://vuejs.org/v2/examples/select2.html

It explain several caveats and how to handle it properly. I highly recommend you to take a look at that.

For a quick solution, you can try adding this code to the page component's mounted hook:

<template>
...
</template>

<script>
export default {

    // ... other code in your page component

    mounted() {
            $("a.single_image").fancybox();
    },

}
</script>

This is a very simple solution to illustrate how you would start integrating this, please note:

  • This is not an optimal solution
  • this can lead to memory leaks and then lead your site to be unusable
  • jQuery must be available to this page, google on how to inject it on nuxt, I really don't remember how to do that, maybe you can just add import 'jquery' to this page, but I guess there is a better way

Hope it helps =)

Please or to participate in this conversation.