Having trouble getting Vue.js to cooperate with a brand new Laravel 5.8 setup?

I set up a fresh Laravel project using laravel new sample. Then I executed npm install followed by npm run dev. Next, I modified the welcome.blade.php file as shown below:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" href="{{ mix('js/app.js') }}"></script>
    </head>
    <body>
        <div id="app">
            <example-component></example-component>
        </div>
    </body>
</html>

However, upon making this change, the page remains blank and the Vue devtools extension in Chrome displays "Vue.js not detected". Even though Laravel usually pairs well with Vue, it seems like something is amiss. Below are the original files provided by Laravel without any alterations.

/resources/js/app.js (which compiles successfully to /public/js/app.js using npm run dev)

// JavaScript dependencies loading block

require('./bootstrap');

window.Vue = require('vue');

// Automatic component registration code block

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

// Fresh Vue application instantiation

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

/resources/js/components/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>

webpack.mix.js:

const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application.
 |--------------------------------------------------------------------------
 */

mix.js('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.scss', 'public/css');

package.json:

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        ...
    },
    "devDependencies": {
        "axios": "^0.19",
        "bootstrap": "^4.1.0",
        ...
    }
}

These files are all in their default state after installation. Any thoughts on why the page fails to render properly despite loading the compiled app.js? The file appears correct with references to Vue and example-component.

Answer №1

Ensure your script is deferred

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

The purpose of this is as follows:

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

Javascript will be loaded immediately, potentially before the element #app is ready. By deferring, the JS code will only run after the document has fully loaded.

If needed, you can also utilize jQuery with $(document).ready to ensure the document is fully loaded (though jQuery is not necessary unless used elsewhere).

No jQuery required:

Edit: As mentioned by @swonder, moving the script to the bottom of the body will also execute it after the DOM is fully loaded.

Answer №2

Don't forget to include a forward slash '/' when linking the app.js file

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

If the project is having trouble locating the app.js file, it may be due to an incorrect path. You can troubleshoot this by pressing ctrl+u and verifying the js file's path.

Answer №3

Give this a shot:

<script href="{{ asset('js/app.js') }}" defer></script>
placed within the head section of your document, such as in app.blade.php

Answer №4

Make sure to follow these steps in the specified order

First, ensure that your application URL is correctly set in the .env file. For instance, if you have installed Laravel in a folder named test,

APP_URL=http://test.local/test/public/

Note: When including scripts, use the src attribute in the script tag and not href

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

Verify that your app.js file is loading correctly by checking the developer console.

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

Upon initializing gitbook, an error occurs stating "Error loading the latest version"

After meticulously following these instructions, step by step: mac OS 10.13 nodejs v8.7.0 npm 5.5.1 CLI version: 2.3.1 GitBook version: 3.2.3 I encountered this "gitbook init" error at the end: Error loading version latest: Error: Cannot find ...

Adjust the size of icon passed as props in React

Below is the component I am working on: import ListItemButton from '@mui/material/ListItemButton'; import ListItemIcon from '@mui/material/ListItemIcon'; import Tooltip from '@mui/material/Tooltip'; const MenuItem = ({data, o ...

Passing data between parent and child components within an Angular application using mat tab navigation

I am currently working on a project, which can be found at this link. Current Progress: I have implemented a mat tab group with tabs inside the app-component. When a tab is clicked, a specific component is loaded. Initially, most of the data is loaded in ...

Having trouble with next.js and MongoDB integration? Encountering an error during the `next build` process?

Having trouble setting up a next.js project with MongoDB integration. The issue seems to be related to the build process and the error logs are not very helpful in pinpointing the problem. Here is a snippet from the log: 0 info it worked if it ends with ok ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

Is there a way for the React select component to adjust its width automatically based on the label size?

After defining a React select component, it looks like this: <FormControl> <InputLabel id="demo-simple-select-label">Age</InputLabel> <Select labelId="demo-simple-select-label" id=&quo ...

Verify if a fresh message has been added using AJAX

Is it possible to create a notification system similar to Facebook, where the tab title displays the number of new messages without refreshing the entire page? Below is a snippet of code from my website's message box feature that I am working on. < ...

You are limited to storing only up to 2 items in the localStorage

My goal is to save items in local storage as an array of objects. Initially, it works perfectly and stores the first element in local storage as needed. However, I am facing an issue where I cannot store more than one element. Below is the code block that ...

Custom sample rate options in RecordRTC allow for the recording of silent audio tracks

I am currently working on implementing RecordRTC.js to capture audio from a microphone and then upload it to a server built with nancyfx. Initially, I am simply aiming to upload the audio stream and store it in a wav file for testing purposes. However, my ...

Combine two arrays of objects and merge properties using the Ramda library

I have two arrays as shown below: ['TAG.u', 'TAG.c'] and the other one is: [{name:'some',key:'TAG.u'}, {name:'some new', key: 'TAG.b'}, {name:'some another' , key:'TAG.c'} ...

store in database utilizing ObjectModel

I am utilizing ObjectModel to store form data in a database. However, I have encountered a simple issue with my function: class AddFonction extends ObjectModel { public $id_customer; public $fonction; public $id_gender; public $firstname; ...

Unlock the npm package on TFS

Encountering an issue with a npm package called tfs-unlock while using grunt. Upon trying to build, the server returns the following error message: [exec] [4mRunning "tfs-unlock:checkout" (tfs-unlock) task[24m [exec] [31m>> [39mChild process exi ...

Utilizing distinct JavaScript, JQuery, or CSS for individual Controllers within the Codeigniter framework

Currently, I am involved in a Codeigniter v3 project where we are developing a comprehensive application for a large organization. To optimize the loading speed of each page, I am looking to integrate custom JQuery and CSS files/code specific to each Con ...

A guide on sorting an array based on elements from a different array

We are currently in the process of developing an application using Vue and Vuex. Our goal is to display a list of titles for venues that a user is following, based on an array of venue IDs. For instance: venues: [ {venue:1, title: Shoreline} {venue:2, ti ...

Fixing the problem of digest overflow in AngularJS

I've been working on a code to display a random number in my view, but I keep encountering the following error message: Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! It seems to be related to a digest outflow issue, and I&apo ...

Is it considered acceptable in React for the value of one state to be determined by another state?

Consider this scenario: state1 tracks the mouseover of clientX and clientY, while state2 retrieves the value from state1 upon clicking. Is this implementation acceptable? const [move,setMove]=useState([]) const [click,setClick]=useState([]) useEffect(() ...

Having trouble with preventDefault() not working during a keyup event?

I am struggling to make preventDefault() function properly. Here are a few variations of the code that I have attempted: First: $(document).keyup(function (evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode == 192) { ...

Deactivating a button if the input fields are blank using ReactJS

Hi there, I'm new to reactJS and recently encountered an issue with my code. Everything seems to be working fine except for the NEXT button not being disabled when text fields are empty. My expectation is that the NEXT button should only be enabled af ...

Updating the quantity of a product within a state in React allows for easy manipulation of that

My scenario involved attempting to reduce the quantity of a product object in the UI by clicking a button, but the quantity did not update as expected. What is the recommended course of action in situations like this? let product={ a:1,b:2,c:3}; For examp ...

What steps can be taken to avoid including empty tasks in React code?

Is there a way to prevent my application from adding empty tasks? Below is the code snippet for adding a new task to an array. How can I implement a condition to block the addition of empty tasks? This application follows Mozilla's guidelines for a R ...