Unable to retrieve VueJs instance variable outside of main.js file

I have a list of fruits saved in a file named fruit_list. The file contains the following information.

    export default {
      fruits: [
        'APPLE',
        'BANANA',
        'CHERRY',
        'GRAPE',
        'KIWI',
        'MANGO',
        'ORANGE',
        'PEAR',
        'PINEAPPLE',
        'STRAWBERRY',
        'WATERMELON'
    ]
}

In the index.js file, I imported this list and assigned it to a variable:

import fruitList from './config/fruit_list';

Vue.prototype['$fruitData'] = fruitList;

Now I am attempting to access this variable $fruits in a script called operations.js using the following code:

export const checkFruitIncluded = (fruit) => {

    const fruits = this.$fruitData.fruits;
    
    return fruits.includes(fruit);
}

This function checkFruitIncluded is then invoked from a functionality.

However, I encountered an error stating

Uncaught TypeError: Cannot read property 'fruits' of undefined

As a beginner with VueJS, any help in identifying what's lacking here would be appreciated.

Answer №1

When working with separate files like utils, the vue instance may not be accessible outside of the component hierarchy. One way to address this issue is by passing global data as a parameter when calling utility functions:

this.isCountryIncluded = checkCountryIncluded(this.$countryData,this.country)

Here is an example from utils.js:

export const checkCountryIncluded = (countryData,country) => {

    const countries = countryData.countries;
    
    return countries.includes(country);
}

Answer №2

Make sure to use the component context when calling the checkCountryIncluded function.

this.isCountryIncluded = checkCountryIncluded.apply(this, [this.country])

In order for this code to function correctly, the checkCountryIncluded function must be a regular function and not an arrow function, as arrow functions do not allow for changing the context.

export const checkCountryIncluded = function(country) {

    const countries = this.$countryData.countries;
    
    return countries.includes(country);
}

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

The rendering of Vue-bootstrap is not functioning correctly

I recently set up a new webpack project using Vue and Bootstrap. However, it appears that the styling for bootstrap elements such as b-nav, b-nav-item, and b-badge is not displaying correctly. This issue seems to affect most other element types as well. Y ...

Utilizing 'this' in jQuery plugin parameters: A step-by-step guide

Currently, I am developing a jQuery plugin and encountering an issue with the $(this) selector being undefined in one of the parameters. My code looks like this: $('.foo').loadMore({ onScreen: function() { $(this).css('backgrou ...

Tips on how to modify a select option in vue based on the value selected in another select

My Web Api has methods that load the first select and then dynamically load the options for the second select, with a parameter passed from the first selection. The URL structure for the second select is as follows: http://localhost:58209/api/Tecnico/Tanq ...

Execute the cucumber tests based on tags or run all the tests

I am facing challenges when it comes to running cucumber tests. I aim to execute either all scenarios if tags are not provided as a CLI argument, or specific scenarios based on the passed tags as CLI arguments. Here is my configuration file: module.exports ...

One div takes a backseat to the other div

I recently delved into learning Bootstrap, but I'm baffled as to why one div is appearing behind another. <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fa ...

Having trouble retrieving array information in Javascript

I've recently started learning programming and JavaScript, but I'm struggling to access data within an array. Below is a snippet of my code: global.arr = []; var id = 12; for (var i=0; i<5; i++) { arr.push(id); id++; } console.log(arr) ...

Angularjs still facing the routing issue with the hashtag symbol '#' in the URL

I have recently made changes to my index.html file and updated $locationProvider in my app.js. After clicking on the button, I noticed that it correctly routes me to localhost:20498/register. However, when manually entering this URL, I still encounter a 4 ...

Is there a solution to fix the issue with IE causing hover effects not to

I'm currently in the process of designing a website, and I have implemented some image hover effects that reveal elements within the image when you hover over it. These effects are functioning correctly on Chrome, Safari, and Firefox; however, they ar ...

Integrate jQuery into a Vue.js 2 project using the expose-loader plugin

For my latest Vue.js project using the vue-cli, I attempted to import jQuery with expose-loader. Following the instructions in the official documentation, but unfortunately, I was not successful. Here are the steps I took: Installed jQuery and expose- ...

"Want to know the best way to retrieve the most recent form input value using jQuery or Javascript

I've been reading a lot about using jQuery to set and get field values, but I'm encountering an issue where I can't retrieve the value after submitting, editing it in an input field, and then submitting again. It works the first time, but no ...

Encountering a connection error while running a Node.js Selenium test case on Chrome. The specific error message received is: "Error: ECONNREFUSED - Connection refused to 127.0

When attempting to run a test case on a Selenium Node.js server, an error was encountered: Error: ECONNREFUSED connect ECONNREFUSED. The test case script is as follows: var assert = require('assert'), test = require('selenium-webdriver ...

Implementing Ajax to insert information, however, the process is prolonged for data insertion

When I use AJAX to insert data into MySQL, pressing the submit button is causing delays in data insertion. I'm hoping someone here can provide better suggestions or feedback. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.m ...

Transferring variables between vanilla JS and Angular 2: A guide

I am facing a challenge where I need to retrieve an object title from vanilla JavaScript and then access it in my Angular 2 component. Currently, I am storing the variable in localStorage, but I believe there must be a better approach. The issue arises wh ...

Transforming CSV CSS values with jQuery's CSS method: Step-by-step guide

My goal is to stack multiple background images within a single div container while ensuring their position is relative to the screen height. The problem I'm encountering is my inability to modify CSS values separated by commas. Here is my logical appr ...

Guide to implementing a feature where clicking on a specific section of the background image triggers a transition to another website using HTML

Is it possible to set up a background image with clickable regions that direct users to specific websites? ...

Vuejs - The router is not rendering the third component in the app, even though the first two components are functioning properly

After creating my very first Vue app, I encountered an issue with the router. While the first two components function perfectly, the third one does not seem to work as expected. Below is a snippet of my code: index.js import Vue from 'vue' impo ...

Can you explain the distinction between the GenerateSW and InjectManifest choices within the vue ui pwd configuration?

Currently utilizing @vue/cli for building a vue project. I have initiated vue ui to access the vue UI and am in the process of customizing various available options. https://i.sstatic.net/h77AE.png Within Configuration -> PWA, I have come across the a ...

The Magnificent jQuery Widget Factory's _trigger Instance

When utilizing the _trigger function to initiate events, I often come across a recurring issue that I struggle to fully comprehend. The problem arises when there are multiple instances of my widget on the same page. In such cases, the most recently instan ...

Enclose several lines of text within a border in the midst of other content

I'm looking to add a stylish border around multiple lines of text in a paragraph without having the border appear on each line individually. While I could enclose all the text in a div, it would separate the content from the rest of the paragraph. W ...

Is it possible to display data on a webpage without using dynamic content, or do I need to rely on JavaScript

Imagine a scenario where I have a single-page website and I want to optimize the loading time by only displaying content below the fold when the user clicks on a link to access it. However, I don't want users with disabled JavaScript to miss out on th ...