Laravel 5 mix app.js file creation

2019-07-30 07:49发布

I created a custom JavaScript file with a simple function:

function picture(soemthing){
    document.getElementById('idXYZ').src = "example.com";
}

Then I added this file to the webpack.mix.js config:

mix.js(['resources/assets/js/app.js', 'resources/assets/js/xyz.js'], 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css');

and run: npm run dev. npm compiled my script and the picture function was included in the app.js file. Now I'd like to use the "picture" function in a blade.php but whenever I call it I get "Uncaught ReferenceError: picture is not defined". I checked the page source and found that the picture function is wrapped with a different function

(function(module, exports) {
    function picture(soemthing) {
        document.getElementById('idXYZ').src = "example.com";
    }
}) 

Should I add some additional namespace before calling the picture function from blade.php or I have something wrong with mix configuration?

1条回答
Emotional °昔
2楼-- · 2019-07-30 08:05

The functions and classes are not exposed to the public, so all JavaScript logic should be written in the JS files. If you insist on writing JavaScript logic in the blade file, you could attach the function to the window object.

window.picture = function picture(soemthing){
    document.getElementById('idXYZ').src = "example.com";
}

...

window.picture()
查看更多
登录 后发表回答