The challenge of incorporating Laravel, Vue, and JavaScript into a Blade template

It may seem like a silly question, but I am struggling to find a solution. My goal is to load a Vue component and JS file into a blade view. When I include the following:

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

The selectize_settings.js file loads successfully, but not the Vue component. When I include 'defer' like this:

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

The Vue component loads, but the selectize_settings.js file does not (ReferenceError: $ is not defined). This is because jQuery has not been loaded through app.js when selectize_settings.js is loaded.

Here is the code from app.js:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');
import BootstrapVue from 'bootstrap-vue'

Vue.use(BootstrapVue)
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import 'selectize/dist/css/selectize.default.css'

window.$ = window.jQuery = require('jquery')
require('selectize');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

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

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

Here is the code from test.blade.php:

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>
    <script src="{{ asset('js/selectize_settings.js') }}"></script>
    <script src="https://kit.fontawesome.com/4262f4e15a.js" crossorigin="anonymous"></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">


</head>
<body>
    <div id="app">
        <div class="control-group">
            <label for="select-beast">Beast:</label>
            <select id="select-beast" class="demo-default" placeholder="Select a person...">
                <option value="">Select a person...</option>
                <option value="4">Thomas Edison</option>
                <option value="1">Nikola</option>
                <option value="3">Nikola Tesla</option>
                <option value="5">Arnold Schwarzenegger</option>
            </select>
        </div>
        <div class="vue-comp">
            <example-component></example-component>
        </div>
    </div>
</body>
</html>

Here is the code from selectize_settings.js:

$( document ).ready(function() {
    $('#select-beast').selectize({
        create: true,
        sortField: {
            field: 'text',
            direction: 'asc'
        },
        dropdownParent: 'body'
    });
});

And the code from ExampleComponent.vue:

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">Example Component</div>

                    <div class="card-body">
                        I'm an example component.
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>

I appreciate any help or guidance you can offer. Thank you!

Answer №1

Give this a shot in your app.js file:

//...
global.$ = global.jQuery = require('jquery');
//...

Consider removing the defer attribute as well:

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

Answer №2

Here is a suggestion for you:

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

Answer №3

Success! The code is functioning properly with the addition of defer to the JavaScript file.

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

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

Tips for utilizing a button within a hyperlink in a React component:

I am new to react and have been working on the following code: import {NavLink as Link} from 'react-router-dom' return ( <div> {posts.map((actualData, index) => ( <Link to={'/' + actualData.id}> <d ...

How to trigger a JavaScript function using a link in CakePHP?

When working with Html, <a href="some_url"> Contact Seller </a> In the realm of Cakephp, <?php echo $this->Html->link('Contact Seller', array('controller'=>'pages', 'action'=>'conta ...

The loop is being controlled but the data is not being added and shown in the HTML div

I am struggling to display JSON data in an HTML div using a for loop. While my control is entering the loop, the data is not being appended and displayed in the HTML div. Here is the JSON data: [{"id":"15","FirstName":"ranjan","MiddleName":"","LastName": ...

Is it possible for a conditional type in TypeScript to be based on its own value?

Is it possible to use this type in TypeScript? type Person = { who: string; } type Person = Person.who === "me" ? Person & Me : Person; ...

Is it possible to retrieve JSON data and display only the entries with positive values in an HTML

I am working on a project that involves fetching JSON API data and displaying it in an HTML table, but only for values above 10. Below is the code snippet along with my JavaScript. I specifically want to exclude negative values and only display positive v ...

Unexpected server failure due to a new error occurring in the asynchronous authentication login function

This problem is really frustrating... I'm having trouble with a throw exception that causes my express server to crash in my async login function. The issue here is that the error isn't caught by the try/catch block. Even though the user data is ...

How can I reduce the delay in Angular 5 to a minimum?

The following code represents a simple request function: getItem() { return this.http .post<ItemModel>(`${this.apiUrl}/${methodUrl}`, {}) .subscribe(response => { ... }); } Depending on the duration of the ...

Fulfill a pledge after a function has been run five times

I'm struggling to understand why my promise is not working as expected and how to resolve the issue. Here is the code snippet: let count = 0; function onLoad(){ count++ console.log(count); return new Promise((resolve) => { ...

Form a collection using multiple elements

I'm attempting to combine multiple arrays into a single array. For instance : array1= ['Joe','James','Carl','Angel','Jimmy',]; array2= ['22','11','29','43',&apo ...

Exploring keys rather than values in Vue application

Currently, I am facing an issue where I am retrieving the values for three keys from my API using Axios. However, each time I make a request, the values are being displayed four times for each key. After removing one key from my data models and retesting, ...

What is the process for extracting dates in JavaScript?

I need help extracting the proper date value from a long date string. Here is the initial date: Sun Aug 30 2020 00:00:00 GMT+0200 (Central European Summer Time) How can I parse this date to: 2020-08-30? Additionally, I have another scenario: Tue Aug 25 ...

Modifying linked dropdown selections with jQuery

I'm trying to create a recurrent functionality where I have 3 select elements. When the first select is changed, it should update the second and third selects accordingly. If the second select is changed, then it should also affect the third select. ...

Issues with returning a response in AWS Lambda using NodeJs

I have been experimenting with a basic Node Js example on AWS Lambda that includes the Async library. The code seems to be functioning correctly, however, for some reason, the Lambda Function is returning a null response. As a newcomer to Node, I could use ...

Is there a way to send a multi-dimensional array using jQuery ajax?

I am encountering an issue with posting an array as a JavaScript variable {{0,0},{1,1},{2,2}} using JSON.Stringify. Whenever I try to post it, I receive an internal server error 500. Can someone please advise on how I can successfully post and utilize this ...

When trying to use express, the error message "d3.scale is

Having trouble integrating a c3-chart into my web application using node.js and express. The c3.js file is throwing the error message: TypeError: d3.scale is undefined Here is an excerpt from my layout.yade file: doctype html html head title= titl ...

Unable to retrieve the /socket.io/socket.io.js file in the client-side application

My server side application is currently hosted on heroku: The code snippet that is relevant to this issue is as follows: const express = require('express'), app = express(), server = require('http').createServer(app), ...

Configuring Access-Control-Allow-Origin does not function properly in AJAX/Node.js interactions

I'm constantly encountering the same issue repeatedly: XMLHttpRequest cannot load http://localhost:3000/form. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefor ...

The title of the Electron application remains consistent

My application is being packaged using electron-packager, but it's not changing its name and still displays "Electron." It's supposed to use the productName in my package.json file, but for some reason, it doesn't change. Even after creati ...

Challenges with implementing speech recognition within a React component's state

I've encountered an issue with the React library react-speech-recognition. When trying to modify the newContent state within useEffect, it ends up printing as undefined. Additionally, I'm facing a similar problem when attempting to update the sta ...

The error message "vue nuxt TypeError: Cannot access 'mounted' property of undefined" is displayed

I am attempting to implement authentication using Keycloak with Vue Nuxt following the guide at However, when I try to log in, it fails and displays the following error: TypeError: Cannot read properties of undefined (reading 'mounted') at A ...