Utilizing Nuxt JS to leverage injected functions from one plugin within another plugin file

I recently implemented Nuxt JS's inject feature to add a reusable function to my page. However, I'm facing challenges trying to utilize this function in another plugin file. Here's the setup:

  • plugins/utils/tracking.js
function setCookiePrefix () {
  return 'fudge__'
}

function getCookie (app, name) {
  try {
    const prefix = setCookiePrefix()
    const cookie = app.$cookies.get(`${prefix}${name}`)

    if (!cookie || cookie == '') {
      throw 'cookie not set'
    }

    return cookie
  } catch (err) { }

  return null
}

export default function ({ app, store, context }, inject) {

  /*
  * Get just the affiliate (cpm_id OR affiliate)
  * examples: "my_brand", "blah"
  */
  inject('getAffiliate', () => {
    const affiliate = getCookie(app, 'affiliate')
    const brand = getBrand(store)

    if (!affiliate) return brand
    
    return affiliate
  })

}

Now, when trying to use the getAffiliate function from my tracking.js file in another plugin file:

  • plugins/init-brand.js
export default async function ({ app, route, store }) {
  const affiliate = app.$getAffiliate()
  console.log(affiliate) <-- shows undefined
}

I've attempted different methods such as:

  • app.$getAffiliate()
  • this.$getAffiliate() <-- this works in a Vue file
  • $getAffiliate()
  • this.getAffiliate()

What step am I missing to access the getAffiliate function in another plugin file?

Answer №1

I've implemented an API plugin with Axios and set it up to be loaded inside another plugin file like so:

export default ({$api}, inject) => {
  const service = new SomeService($api)
  inject('someService', SomeService)
}

In your scenario, it would look like this:

export default async function ({app, route, store, $getAffiliate}) {
  const affiliate = $getAffiliate()
  console.log(affiliate)
}

I can't confirm if this is the correct approach, but it's working well for me.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the proper way to implement the <slot> element within templates?

I've been exploring the functionality of <slot> in Vue templates, and from what I gather, slots allow for passing child content within a component to the template. Here's a brief example that demonstrates this concept (also available on co ...

Utilize Restangular to send data as a payload rather than a query string

Currently, my backend service is set up to register a new user in our system using the following URL: /api/users/register When using Restangular, post requests are typically sent as either query string: Restangular.all('users').post("register" ...

Moving a DIV below a fixed-positioned element

I have a website with a scrollable div. It works well, but I also need an absolutely positioned div on top of it - and it still needs to scroll smoothly without any hindrance. You can check out a basic JSFiddle demonstration here: http://jsfiddle.net/41ra ...

Ensure that a new window is opened while maintaining the exact location of the parent window

Having an issue with printing a calendar. The problem arises when trying to load CSS with absolute paths like /path/to/css.css. Opening a window with: var win = open('', '_blank') win.document.write(htmlContent) will display the HTML ...

What is the best way to hide a button from view while still allowing it to be accessed by JavaScript?

I need to create a button that is invisible and will be triggered by a JavaScript function. <asp:Button ID ="btnDummy1" runat="server" Visible ="true" OnClick="btnSubmit1_Click" width="0px" height="0px"/ Setting 'visible = false' doesn&apos ...

AngularJS - using ng-repeat before initializing the scope variable

Currently, I have set up a md-tabs configuration, which is bound to $scope.selectedIndex for the purpose of being able to change it programmatically. The process involves using a button to trigger a function that updates data. Subsequently, I modify $scop ...

Is resizing possible using the Canvas identifier?

Is it possible to adjust the canvas size to match the width of the page using the canvas id's style in the html? Then in your javascript code for the canvas, can you have resize listeners that are responsive to the canvas size at any given time? I c ...

React functional components with checkboxes can trigger rerenders

I'm currently working with Gatsby and have a functional component that iterates through a set of data to generate a radio button group with an onchange event and a checked item. Whenever I update the state, the entire page component re-renders. I thou ...

Backend JS error found in Joomla 3.0 Component

Currently, I am working on developing a custom Joomla 3.0 component. To begin, I started by downloading the com_hello component sample from the official Joomla documentation. However, I've encountered an issue when trying to check the checkbox in the ...

Working with Mongoose: updating a document and retrieving a particular section

I need help with my chat app development. Specifically, I am facing an issue while updating the conversation model. I want to retrieve the newly added message along with its generated _id and createdAt fields from the messages array in Mongoose. To achiev ...

Is there a way for me to use an ajax xmlhttprequest to submit all the selected values from my radio buttons?

Here's the situation: I have four input forms [A-D] and I have selected options A and B. I want to transfer this information to another page, but I'm not sure how to do it. I've tried searching for tutorials on AJAX, but most of them focus ...

Loading dynamic Vue JS components into specified elements is a powerful feature that allows

Below is the code snippet I am using: let templateName = '#' + className + 'Properties'; const vue2 = { template: templateName, el: "#app2" }; var vm = new Vue(vue2).$mount(); Each t ...

Locate the parent element that has the smallest amount of space taken up by its child elements

My goal is to determine which container, among several <divs>, each containing multiple child <divs> of varying sizes, has the smallest amount of space covered by the child elements. <div class="container" id="first"> ...

Limiting the amount of tasks in order to manage memory consumption

My web application loads entire files into memory on each request and performs asynchronous tasks with their contents. I'm concerned about running out of memory, so I want to restrict the number of files processed simultaneously. If file sizes were kn ...

Enhance global variable by appending a line from a local function in Javascript

In my js files, I have some global functions that are used in all modules of the application. Currently, I am working on a module that requires modifying one of these global functions to run a local script every time it is called. The issue is that the g ...

Using the Set function to compare distinct elements within different arrays

Update: After reviewing the link shared by faintsignal, it appears to be the most suitable answer. It not only clarifies why this behavior is happening but also provides a solution to the issue at hand. I am currently working with an array and trying to d ...

Implementing MUI createTheme within Next.js

After switching from material-UI version 4 to version 5.5.0 in my project, I encountered issues with createTheme. The colors and settings from the palette are not being applied as expected. Current versions: next: 11.0.0 react: 17.0.2 mui : 5.5.0 theme. ...

Unable to achieve the desired focus on a specific element using JavaScript's .focus() method

After executing the command $('#someelement').focus(), I am not receiving any error message but the functionality is not working as expected. Even when I attempt to retrieve document.activeElement, it continues to return the body element. Here i ...

Validating usernames using Jquery's remote method检verifying the username

Struggling with the validation plugin and Laravel 4.2. I've been attempting to use ajax to check the username, but it's not functioning as expected. No matter if the username exists or not, it always appears available. Another problem arises whe ...

Inconsistent CSS3 transitions behavior in Firefox 4

I have been playing around with some css3 transitions and created a slider test. It works perfectly in webkit browsers, but I have noticed an issue in Firefox 4. When clicking on the left link for the first time, the slider is supposed to slide to the left ...