When attempting to call a function from a separate JavaScript file in Vue, the returned value is showing

My goal is to trigger my notification function from another JS file, but I keep getting an undefined error.

The code snippet for the notification function in notification.js is as follows:

function notification(message, level = 'success') {
    Lobibox.notify(level, {
        delayIndicator: false,
        msg: message

    });
}

In addToCart.vue, I have the following code:

<template>
    <div>
    <button class="button dark small" @click="addToCart(menu, price)">
        <i class="fa fa-cutlery fa-lg m-right-5"></i>
        Pilih Menu
    </button>
    </div>
</template>

<script>
    export default{
        props: ['menu', 'price'],

        methods:{
            addToCart(menu, price){
                const currentPoint = $('#current_point').val();

                if(price > currentPoint){
                    return notification('Point is not enough', 'error')
                }


            }
        }
    }
</script>

In app.js, the Vue component is added and initialized:

Vue.component('addtocart', require('./components/AddToCart.vue'));
new Vue({
    el: '#app'
});

The script tags to include the necessary files in html are shown below:

<script src="{{ asset('js/notification.js') }}"></script>
<script src="{{ asset('js/app.js') }}"></script>

However, every time price > currentPoint condition is met, I encounter the error:

Uncaught ReferenceError: notification is not defined
.

I am using LaravelMix for compilation. Any suggestions on how to resolve this issue?

Answer №1

notification.js

function displayNotification(msg, type = 'info') {
    Lobibox.notify(type, {
        delayIndicator: false,
        msg: msg
    });
}

window.displayNotification = displayNotification;

Figure it out. I must include

window.displayNotification = displayNotification
to make it accessible from any part of the code.

Answer №2

It appears that all you have to do in your HTML is:

<script src="js/notification.js"></script>
<script src="js/app.js"></script>

Answer №3

Avoid placing objects in the window, as it is not recommended.

It appears that you are utilizing Vue with webpack. If you are not, this method may not be compatible. It is advisable to use ES6 modules for better access to resources.

In your notification.js file:

export default user

This can then be invoked using:

import notification from 'notification'

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

Creating a GWT-compatible solution for implementing the Google Visualization - Annotation Chart

I am currently using the newly launched Annotation Chart in GWT by integrating native JavaScript. I have managed to display the example chart successfully, but unfortunately, it lacks interactivity and behaves more like an image. Can anyone provide guidanc ...

The data array generated from an axios request is not being rendered properly on the chart using Chart.js

I am facing an issue with my API endpoint that returns an array of 24 values which I want to utilize in a chartjs within a vue component. Despite no errors on page load, the bars on the charts are not displaying and the reason remains unknown to me. UPDA ...

Tips for utilizing the /foo-:bar pathway in Nuxt.js?

I am trying to utilize the router /foo-:bar in Nuxt. Do you have any suggestions on how I could make this work? I attempted using pages/foo-_bar.vue but it did not yield the desired results. ...

The functionality of res.send is not working correctly

Attempting to send a response from my express application to the front-end in order to display an alert. Here is what I have attempted in my app: if (info.messageId) { res.redirect('back'); res.send({ success: true }); } ...

Exploring Angular Factory: Creating the getAll method for accessing RESTful APIs

In my Angular.JS factory, I am retrieving data from a REST Api. The REST Api endpoint is "/api/getSsls/1", where 1 represents the page number. The API response is in JSON format and contains the first ten items along with total pages/items information. I ...

Using JSP in combination with JavaScript for creating dynamic templates

Implementing server-side HTML templating with JSP + JSTL allows for the generation of tables containing user data: <body> ... <table> <c:forEach items="${users}" var="user"> <tr> <td>${user ...

Using Object.defineProperty in a constructor has no effect

I recently revamped my three.js project and ran into a peculiar issue where all objects were being rendered with the same geometry and material. Upon further investigation in the debugger, I narrowed down the problem to this constructor: function Geometry ...

Combining Multiple Pie Charts with a Line Chart in Highcharts

Can anyone provide guidance on creating a chart similar to the one shown in the Highcharts library? https://i.sstatic.net/BoX4i.jpg ...

Dividing JSON information into parts

I am attempting to present a highchart. I have utilized the following link: Highchart Demo Link Now, I am trying this web method: [WebMethod] public static string select() { SMSEntities d = new SMSEntities(); List<str ...

What could be causing my NextAuthJS discord login to function in the test environment but fail to deploy in production on NextJS 13?

After attempting to deploy my NextJS application on Vercel, I encountered a problem with the AuthJS sign-in model. While running the program using npm run dev, everything works smoothly and I can log in to my Discord account linked to the developer portal& ...

A guide on how to modify a CSS property to set the display to none upon clicking a radio button

Currently, I am attempting to display two input boxes in a table when I select specific radio buttons and hide them if I choose another option. The code I have does work but has a minor issue, function disappear() { document.getElementsByClassName("ta ...

Incorporating tab navigation and drawer navigation in a React Native Expo application

I am encountering a warning in my react native expo app that uses react navigation 6. Even though I am able to display the tabs and the drawer, I keep getting this console alert: Found screens with the same name nested inside one another. Check Home, Home ...

Transform special characters into HTML entities

$scope.html = '&lt;script&gt;'; Is there a way for Javascript to convert &lt;script&gt; back to <script>, similar to how PHP does it? ...

Utilizing a Material UI custom theme in React with Typescript: A step-by-step guide

Upon using the tool , I received a js file and a json file following the paths mentioned on the theme generator page: // src/ui/theme/index.js /* src/ui/theme/theme.json */ The files operate smoothly when left with the .js extension. However, when I attem ...

If the href attribute is set to "#" or the target attribute is set to "_blank", then the <a> request cannot be prevented

I have a registration site that triggers a warning window whenever a user clicks on any link during the registration process. However, I want to exclude <a> tags with href="#" and target="_blank" attributes from this behavior. Essentially, I want to ...

After submitting the form, I must only deactivate the checkbox that has been selected

Here is the HTML code I am working with: I have multiple checkboxes designed as buttons to select a room, but it's quite annoying when they all get selected at once. $("form").submit(function() { $('.seat input:checkbox').prop("disable ...

The AJAX callback is unable to access the method of the jQuery plugin

I have a scenario where I am fetching data from an AJAX response and attempting to update a jQuery plugin with that value within the success callback: $.ajax({ url: '/some/url', type: 'GET', dataType: 'json', succ ...

When touch-triggered on IOS, HTML5 Web SQL Transactions were smoothly bypassed without any errors

I'm encountering issues with database transactions on IOS devices. When the user does not interact with the phone, everything functions as expected. However, if the user taps, scrolls, or touches the screen, some transactions bypass the actual transac ...

Checking for the existence of a Vue.js component

In the ready: method of the root instance, I have certain tasks to perform but only if some components are not present (not declared in the HTML). Is there a way to verify the existence of a component? ...

Is there a way to retrieve two arrays in an Ajax request?

JAVASCRIPT CODE: $.ajax({ url: 'assignavailtrainers.php', data: {action:'test'}, type: 'post', success: function(data) { } }); PHP CODE: <?php $username = "trainerapp"; ...