Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function in laravel not defined

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?

like image 502
user1985273 Avatar asked Aug 01 '17 17:08

user1985273


1 Answers

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.

like image 93
apokryfos Avatar answered Oct 23 '22 03:10

apokryfos