12

I added an js method to my app.js:

require('./bootstrap');

window.Vue = require('vue');

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#app'
});

function hello()
{
    alert("hello");
}

Then compiled my assets and added app.js to my view:

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

If i load my view at this point and look at the source i can see the link to app.js and if i open that app.js i can see my hello method in there with a lot of other stuff.

Now when i want to call my method i try to do it like this:

<a onclick="hello();">

But in my console i get an Uncaught ReferenceError: hello is not defined error. What could be the problem?

1 Answer 1

25

Laravel mix tends to compile all js assets into a nice webpackage, however this means that your function is not actually in the global scope because they are all wrapped in immediately invoked function expressions (iife).

You need:

window.hello = function () {
     alert("Hello");
}

However this generally not the best strategy, ideally you'd add an event handler in your vue.

Sign up to request clarification or add additional context in comments.

1 Comment

same goes for vite also

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.