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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With