Vue.js не работает над свежим проектом Laravel 5.8 - PullRequest
2 голосов
/ 17 июня 2019

Я создал новый проект Laravel с laravel new test. Тогда я пробежал npm install и npm run dev. Я изменил файл welcome.blade.php на

<!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>

и это единственное изменение, которое я сделал. Однако страница пуста, и расширения Vue devtools в Chrome говорят "Vue.js не обнаружен".

Поскольку Laravel практически полностью поддерживает Vue, я не вижу, что происходит не так. Соответствующие файлы находятся ниже (не тронуты установкой Laravel).

/resources/js/app.js (который успешно компилируется с npm run dev до /public/js/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');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i);
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default));

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

/**
 * 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.
 */

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. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

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

package.json

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.19",
        "bootstrap": "^4.1.0",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^4.0.7",
        "lodash": "^4.17.5",
        "popper.js": "^1.12",
        "resolve-url-loader": "^2.3.1",
        "sass": "^1.15.2",
        "sass-loader": "^7.1.0",
        "vue": "^2.5.17",
        "vue-template-compiler": "^2.6.10"
    }
}

Опять же, все это просто, когда они установлены.

Есть идеи? Пустая страница успешно загружает скомпилированный файл app.js, который выглядит так, как должен (например, есть упоминания о Vue и example-component).

Ответы [ 3 ]

1 голос
/ 17 июня 2019

Вам необходимо defer ваш скрипт

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

Причина заключается в следующем:

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

Javascript будет загружен, как только онcan и элемент #app, возможно, еще не загружен.При отсрочке JS будет выполняться после загрузки документа.

В качестве альтернативы, вы можете использовать jQuery для ожидания загрузки документа с помощью $(document).ready (но не используйте jQuery, если вы этого не сделаетенужно в другом месте)

без jQuery: https://stackoverflow.com/a/800010/8068675

0 голосов
/ 04 июля 2019

Попробуйте <script href="{{ asset('js/app.js') }}" defer></script> в заголовке документа (как в app.blade.php)

0 голосов
/ 17 июня 2019

Попробуйте добавить косую черту '/' при вызове app.js file

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

Единственная причина в том, что проект не получает правильный app.js путь к файлу. Вы можете выполнить отладку, нажав ctrl+u и проверив путь к файлу js.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...