What could be the reason behind the Vue property being globally undefined in the component at the time of mounting?

Creating a custom Vue plugin was essential for me, which establishes a global property on Vue in this way:

function (Vue, options) {
    Vue.$detector = new TranslatableStringDetector();
}

Utilizing it within a computed property in my component is done like so:

export default {
    // ...
    computed: {
        decoratedProfileName () {
            return this.$detector.decorate(this.$props.profileName);
        }
    }
    // ...
}

Setting it up in the Karma/Mocha test looks like this:

before(() => {
            const localVue = createLocalVue();
            localVue.use(Vuex);
            localVue.use(TranslationDetector);

            store = new Vuex.Store(cloneDeep(storeDefinition));
            store.commit(SET_USER_DATA, userData);

            wrapper = shallowMount(Avatar, {
                localVue,
                store,
                propsData: {
                    id: 0,
                    inputElPrio: 2,
                    profileName: 'Default'
                }
            });
        });

The error occurs during shallowMount() with the following message:

[Vue warn]: Error in config.errorHandler: "TypeError: Cannot read property 'decorate' of undefined"
TypeError: Cannot read property 'decorate' of undefined
    at VueComponent.decoratedProfileName (http://localhost:9877/base/index.js?22adbcd7eb33d018f956122e913fca2646b1c60b:132143:35)
    at Watcher.get (http://localhost:9877/base/index.js?22adbcd7eb33d018f956122e913fca2646b1c60b:71415:25)
   [... more errors ...]
[Vue warn]: Error in render: "TypeError: Cannot read property 'decorate' of undefined"

found in

---> <Avatar> at src/components/controls/Avatar.vue
       <Root>
TypeError: Cannot read property 'decorate' of undefined
    at VueComponent.decoratedProfileName (http://localhost:9877/base/index.js?22adbcd7eb33d018f956122e913fca2646b1c60b:132143:35)
   [... more errors ...]

This inconsistency has left me puzzled. Despite verifying that localVue.$detector is properly configured using console.debug(), I still face issues accessing it as this.$detector within my component. This leads to an unexpected "undefined" result in scenarios such as:

export default {
    // ...
    created: function () {
        console.debug(this.$detector);
    }
    // ...
}

Answer №1

After misunderstanding the information on the Vue.js website, I wrongly interpreted "global" to mean a single object accessible by all components. Following the guidance from the documentation, my intention was to create an "instance method" that would render a property for all components. This subtle distinction proved crucial in solving the issue at hand. Surprisingly, I had overlooked this approach earlier as I was focused on troubleshooting another problem. The correct installation code should be implemented as follows:

function (Vue, options) {
    Vue.prototype.$detector = new TranslatableStringDetector();
}

Answer №2

My understanding is that utilizing lambda functions (also known as anonymous functions) in the lifecycles hooks will not be effective because this references the parent object, which is null.

It is recommended to use function() { /*your code*/ } instead.

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

Display a division in C# MVC 4 when a boolean value is true by using @Html.DropDownList

I have multiple divs stacked on top of each other, and I want another div to appear when a certain value is selected. I'm familiar with using JavaScript for this task, but how can I achieve it using Razor? Below is a snippet of my code: <div id=" ...

Upon clicking a table row, generate a div underneath containing mapped data

My dynamic table is currently being filled with rows based on an array, but I want to display more data in an expanded view when a button in a row is clicked. However, I'm facing challenges as it seems I can't have two table rows within the same ...

Is there a way to pause the execution of code and prompt for confirmation before continuing?

Typically, I utilize the following code snippet in the backend of my application to display a pop-up message to the user after a successful entry has been saved: ScriptManager.RegisterStartupScript(this, this.GetType(), "pop", "<script>alert('C ...

Issue with HighCharts Series Data Points Not Being Added

I am currently facing a major challenge in dynamically changing data for highcharts based on date. To provide context for my project, it involves logging system data with timestamps. I have implemented a date and time picker to specify the start and end da ...

Numerous Axios GET calls made by various components

I am facing an issue where I have two different components rendering on the main screen. Both of them make multiple axios.get requests to fetch data. However, upon initial page load, only the last component successfully retrieves the data while the first c ...

Numerous Fascinating Challenges with React Native

Looking to share my React Native project and seeking help with some issues I'm facing. Despite multiple attempts, I have been unsuccessful in resolving them. Can anyone provide assistance? I have thoroughly searched Stack Overflow for similar questio ...

React - the elusive nature of variable mutation

In my React app, there is a requirement to choose a specific version of a phone and then confirm the selection. Below is an excerpt from the React component's code: const App = () => { const [selectedVersion, setSelectedVersion] = useState(""); ...

Is there a way to verify the file extension in a multi-input form during an upload process?

I am looking for a solution that requests users to upload 4 different files when filling out the form. Check out this example of one of the inputs: <div class="custom-file"> <input type="file" class="custom-file-input" accept="video/*" id="v ...

How to use JQuery to parse an external JSON file with array elements in Javascript

My goal is to extract information from an external JSON file using JavaScript, specifically an array and other elements. The JSON file I am working with is called 'TotalUsers.json' {"@version":"1.0", "@generatedDate":"12/20/10 5:24 PM", "day":[{ ...

Modifying the image height in a column using Bootstrap and JSON data

My webpage is dynamically generating images from a JSON file through a JavaScript file. However, the images are displaying at different heights, and I want each column to adjust to the height of the image to eliminate any gaps. Particularly, data with the ...

React: Why aren't class methods always running as expected?

I created a class component that retrieves a list of applications from an external API. It then sends a separate request for each application to check its status. The fetching of the applications works well, but there is an issue with the pinging process ...

How can I go about refreshing my mapbox gl source data?

Hey there, I'm encountering an issue when attempting to update my mapbox source on click. I currently have two sources (cells, heatmap), and I am trying to add a new source using this code snippet: this.map.addSource("points", { type: "geojson", ...

Calculating the subtotal amount using Vue.js is a straightforward process

My Vue.js project functions as a shopping cart, and I am looking to calculate the subtotal for each product row. Here is an excerpt of my HTML code: <div id="app"> <table border="1"> <thead> <tr> <th>#</th ...

I am experiencing difficulty with the button not responding when clicked, despite trying to implement JavaScript and the Actions syntax

Currently, I am in the process of automating form filling. After filling out the form, there is an update button that changes color instead of clicking when activated. This alteration indicates that the xpath is correctly identified. I have attempted two ...

Could someone clarify why EventEmitter leads to issues with global variables?

I recently encountered an error that took me some time to troubleshoot. Initially, I decided to create a subclass of EventEmitter In the file Client.js var bindToProcess = function(func) { if (func && process.domain) { return process.domai ...

Tips for triggering window load event on a particular page

I need to trigger the windows.load event on a specific page. Currently, I have set it up like this: $(window).load(function(){ if(document.URL == "/car-driving.html") { overlay.show(); overlay.appendTo(document.body); $('.popup' ...

Tag editor assessing the input's width for SO

I've been working on a tag editor similar to Stack Overflow's and it's coming along nicely. The only issue I'm facing is calculating the width of the textbox after a tag has been selected by the user. For each tag added, I try to adjus ...

Issue with jqGrid Multiple Selection

When constructing my jqgrid, I utilize the following code: multiselect: true This enables a check all column. However, clicking the check all checkbox (located at the header) selects all checkboxes, but does not click the checkboxes in each row. You can ...

performing asynchronous iteration with HTTP PUT requests

I'm attempting to send multiple HTTP PUT requests to my server, but I am only able to successfully send one JSON object to the database. What could be missing in my code? var data1 = JSON.stringify(require('./abc.json')), data2 = JSON ...

Is there a way to modify the color scheme of my webpage while utilizing Bootstrap?

As I delve into programming with Bootstrap, I encountered an issue while attempting to change the background color of my body. Even though I used the following CSS code: body { background-color: #eba; width: 100%; height: 100%; } The color change ...