Finding the Vue module within a helper function or mixin: A step-by-step guide

In my development work with Nuxt.js, I am utilizing the cookie-universal-nuxt package to access cookies in both server-side and client-side.

modules:[
  [.....] ,
  [.....] ,
  [.....] ,
  ['cookie-universal-nuxt', { alias: 'myCookie' }],
]

I have a helper function set up as follows:

// helper.js
const func = {
  getSomthingFromCookie(check){
    return this.$myCookie.get('check') === check ? "something" : "else"
  }
}

export default func
// other functions

const mixin = {
  methods: {
 getSomthingFromCookie(check){
    return this.$myCookie.get('check') === check ? "something" : "else"
  }
}
}
Vue.mixin(mixin)
// use this.getSomthingFromCookie outside

This function is then used in various places such as store.js or Page.vue:

// Page.vue or store.js
<div>{{ helper.getSomthingFromCookie("test") }}</div>
..
..
..
..
..
import helper from '~/function/helper.js'


OR

const result = helper.getSomthingFromCookie("test")

However, when trying to run the function, an error occurs:

Cannot read property 'get' of undefined

The issue seems to be that the helper.js file cannot access the Vue instance, specifically the this.$myCookie.

I attempted to resolve this by importing Vue and logging it:

import Vue from 'vue'
console.log(Vue)

But the output in the terminal was not conclusive.

Considering alternate options, I thought about passing the cookie value into the function:

getSomthingFromCookie(check,cookie){
    return cookie === check ? "something" : "else"
  }

However, this approach would require extensive code modifications. Any suggestions or more efficient solutions would be greatly appreciated.

Answer №1

Within your helper.js file, it is important to note that direct access to the vue instance using this binding is not available. Instead, Vue must be imported explicitly.

// helper.js
import Vue from "vue";

const customFunc = {
  getSomethingFromCookie(check){
    return Vue.$myCookie.get('check') === check ? "something" : "else"
  }
}

export default customFunc

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

Having trouble retrieving hidden values from a new Angular/JavaScript window

I have created a form inside a component HTML <button type="button" (click)="myForm(i)"> TypeScript myForm(i) { let form = document.createElement('form'); form.setAttribute('action', this.urlAddr); form.setAttribute ...

Click to open a Swipeable Drawer using an onClick event handler in Material UI

Issue Encountered: Currently, in the provided documentation code (https://codesandbox.io/s/cnvp4i?file=/demo.tsx), the drawer opens when the "Open" button is clicked at the top. However, I am looking to have the drawer triggered and opened when it is direc ...

Error message: "Issue with Jointjs library on Node.js server - Uncaught ReferenceError: Joint is not recognized"

I am attempting to create a sample diagram using the code below on a file hosted on a Node server: <!DOCTYPE html> <html> <head> <title>newpageshere</title> <link rel="stylesheet" href="joint.css" /> <script src="j ...

Library for Nodejs that specializes in generating and converting PDF/A files

Is there a library available that can convert/create a PDF/A file? I've been searching for solutions but the existing answers suggest using an external service or provide no response at all. I heard about libraries in other languages like ghostscriptP ...

JavaScript requires the use of an underscore _ in order to access properties

Recently, I've been working on a code to construct a nested/recursive object/array tree. Upon implementing getters/setters to the object, I noticed that I can only access properties in the root of the tree using the "_" prefix. This becomes apparent a ...

When attempting to log a console statement using Vue Axios, an unexpected error occurs and returns an unexpected

My attempt to display jsonplaceholder posts using axios and vue is resulting in an unexpected console output that points back to the console.log statement. Check out the code snippet below: <script> import axios from 'axios'; export d ...

Angular Error TS2339: The property 'car' is missing from type 'Array of Vehicles'

Encountering Angular Error TS2339: Property 'vehicle' is not found on type 'Vehicle[]'. The error is occurring on data.vehicle.results. Any thoughts on what could be causing this issue? Is the problem related to the Vehicle model? I hav ...

Error in Heroku deployment - Express and React app displaying a white screen

I am encountering a challenging situation as I attempt to understand the issue at hand. Following the deployment of my React/Express application on Heroku, the build and deployment proceed without errors, but the React frontend appears blank. The browser ...

Error in Nestjs Swagger: UnhandledPromiseRejectionWarning - The property `prototype` cannot be destructed from an 'undefined' or 'null' object

Currently, I am in the process of developing a Nestjs REST API project and need to integrate swagger. For reference, I followed this repository: https://github.com/nestjs/nest/tree/master/sample/11-swagger However, during the setup, I encountered the foll ...

Failed to load JSON data from the factory

Recently, I started learning AngularJS and have been struggling to fetch JSON data from a factory. The error message I keep getting is not very helpful: TypeError: Cannot read property '1' of null This is the module I am working with: var app ...

Display and conceal various elements in Vue.js using a data list

I'm a beginner in Vue.js, currently using Vue+Webpack. I am trying to make each link display data based on their respective ids when clicked, and match with the show attribute. I have created this functionality in a .vue file. export default { el ...

Tips on accessing the left value of a absolutely positioned object that transitions on click using getComputedStyle or a similar method

Question: How can I ensure that when the target is clicked, the correct and updated value of the left property is returned? For example, I want it to return 120px if --moved is applied, and 100px if it is not applied. Background: Utilizing getComputedStyl ...

Is there a way for me to retrieve the pageProbs that I have shared with a Component in _app.js?

Upon the loading of my website, I am fetching a large amount of data using getInitialProps. MyApp.getInitialProps = async (appContext) => { // Calls page's `getInitialProps` and fills `appProps.pageProps` const appProps = await App.getInitialProps( ...

Retrieving associate table's record from Vuejs in Laravel collection can be challenging

Struggling with Vuejs and Laravel while developing a live feed app, I've encountered difficulty in accessing associated data from a collection in Vuejs. Is there a simpler way to retrieve this data? Here is my approach: <div class="sl-item" v-for ...

Determine the value of a field by utilizing the values of two other fields through an onChange event

Setting the Stage: Imagine a scenario with 3 key fields: quantity, singlePrice, and totalPrice. I want these fields to be part of my form, with totalPrice being dynamically recalculated whenever quantity or singlePrice changes. My Approach: I created ...

Tips for creating a phone number placeholder that stays in place on a form

I'm looking to display the phone number format as a placeholder in the input field, without it disappearing as the user types. The standard HTML placeholder disappears as the user starts typing. I want the placeholder to remain visible and guide the ...

Retrieve the entity object and convert it into JSON format using json_encode

I have an array that looks something like this: $general_informations['company'] = $company_db In this array, $company_db is an Entity object with properties, such as: $city = $company_db->getCity(); After using json_encode(), I want to re ...

The Objectid seems to be causing issues with the Mongodb find function

I've encountered an issue with my code where I am receiving a null value for the doc. Strangely, when I use findOne({'webpageid':docs[i]._id} and replace docs[i]._id with webpageid, it functions correctly. I have double-checked that docs con ...

Troubleshooting problems encountered when duplicating an array in JavaScript

I am attempting to utilize properties and flatmap to modify an array without altering the original data. I have implemented this method in two different instances within a single dispatch call in Vue.js when transferring data from parent to children comp ...

Ruby on Rails slider bar functionality

Currently, I am developing a video-focused application using Ruby 1.9.2 and Rails 3.1. One of the key features I need to implement is a slider bar that allows users to adjust the total duration of a video in real-time. Despite my attempts to use HTML5 fo ...