Import vue js file to laravel - laravel

I used these vue js files to build my form in Larval.
When I call these files in Larval I get a blank page.
The structure of my files is as follows:
And the contents of app.js file is as follow:
import Vue from "vue"
import App from "./components/App.vue"
import store from "./components/store"
import VeeValidate from "vee-validate"
Vue.use(VeeValidate);
import "./components/directives"
Vue.config.productionTip = false;
new Vue({
store,
render: h => h(App)
}).$mount("#app");
Of course, I get the below warning when I run nmp run watch's command.
WARNING in ./resources/js/app.js 5:8-19 "export 'default' (imported as
'VeeValidate') was not found in 'vee-validate' # multi
./resources/js/app.js ./resources/sass/app.scss
My question is: How to import external vue js files to laravel project?

First thing you need to include app.js to your blade file like this
<script src="{{asset('js/app.js')}}"></script>
after that if you want to use vue js components in you blade app you need to define them in your app.js like this:
Vue.component('home', require('path to your component').default);
and in your blade under div #idd add your tag <home></home>

use src="{{ mix('js/app.js') }}"
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" value="{{ csrf_token() }}" />
<title>VueJS CRUD Operations in Laravel</title>
<link href="{{ mix('css/app.css') }}" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="app">
</div>
<script src="{{ mix('js/app.js') }}" type="text/javascript"></script>
</body>
</html>

Related

Laravel - What settings do I need to make to use my javascript in npm run build mode?

To be honest, I'm having trouble understanding the concept of Laravel how to build in and use its assets (css, js). I guess I'm using a wrong but still working way even for production.
My approach for Production
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
input: [
'resources/css/app.css',
'resources/js/app.js',
],
refresh: true,
}),
],
});
Step 1: npm run build
Step 2: Manually copy the newly generated js and css files into my public folder.
Step 3: Change the file names in my bladetemplate. So app.11111.js to app.js
Note: This doesn't feel right but it worked for Production. I would be very grateful for any hints on this.
Here is my layout.blade.php file
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="stylesheet" href="https://fonts.bunny.net/css2?family=Nunito:wght#400;600;700&display=swap">
<link rel="stylesheet" href="{{ asset('assets/css/main.css') }}">
<!-- Scripts -->
#vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body class="font-sans antialiased">
<div class="min-h-screen bg-gray-100" style="min-height: 100vh; display:flex; flex-direction:column;">
#include('layouts.navigation')
<!-- Page Content -->
<main>
#yield('content')
</main>
#include('templateparts.footer')
</div>
<script src="{{ asset('assets/js/app.js') }}"></script>
</body>
</html>

Vue 3 router with Laravel

I am new to Vue JS and I installed vue 3 with laravel and it shows 404 Not Found. I tried a lot but could not find out the issue.
app.blade.php
<div class="min-h-screen bg-gray-100" id="app">
<!-- Page Content -->
<main>
{{ $slot }}
</main>
</div>
app.js
import { createApp } from "vue";
import router from './router'
import CompaniesIndex from './components/companies/CompaniesIndex'
createApp({
components: {
CompaniesIndex
}
}).use(router).mount('#app')
index.js
import { createRouter, createWebHistory } from "vue-router";
import CompaniesIndex from '../components/companies/CompaniesIndex'
const routes = [
{
path: '/welcome',
name: 'companies.index',
component: CompaniesIndex
},
]
export default createRouter({
history: createWebHistory(),
routes
})
ComponiesIndex.vue
<template>
Hello world
</template>
<script>
export default {
}
</script>
web.php
Route::get('/{any}', function () { return view('app'); })->where('any', '. *');
welcome.blade.php
<body class="antialiased">
<h1>Welcome to Laravel Vue 3</h1>
</body>
I'm not sure, but there is maybe an error in your routes/web.php in where statement, because . * regex should match any string and this is .* without whitespace. Please try:
Route::view('/{any}', 'app')->where('any', '.*');
If you are creating SPA your app.blade.php should not contain any markup, it should be blank HTML template with required script with your app:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="{{ mix('assets/js/app.js') }}" defer></script>
<link href="{{ mix('assets/css/app.css') }}" rel="stylesheet">
</head>
<body>
<noscript>
<strong>We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
</body>
</html>
Then you just mount your Vue app to #app div, which seems to be good in your app.js.

Laravel - Vue component rendering twice because of app.js

I have a Laravel 7 project and installed bootstrap as well as the ui vue auth package. I'm trying to modify the home (home.blade.php) which extends app.blade.php but I've found that somehow the <div id="app"> in app.blade.php is rendering twice. I put a script tag with a console.log() at the bottom of app.blade.php just before the div tag closes and it outputs twice. However, when I put the script tag outside this div it behaves as it should and it only outputs once.
I found out that this is due to a script tag in the head of app.blade.php:
<script src="{{ asset('js/app.js') }}" defer></script>
When I commented that line, everything worked fine! So, my questions are:
Why is this script tag here? Why does it make everything run twice? Do I really need it? Will I encounter problems in the future by not having it?
webpack.mix.js:
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');
resources/js/app.js:
require('./bootstrap');
window.Vue = require('vue');
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
const app = new Vue({
el: '#app',
});
app.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>
<!-- 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">
<!-- Icons -->
<script src="https://kit.fontawesome.com/36a988e261.js" crossorigin="anonymous"></script>
</head>
<body>
<div id="app">
<script type="application/javascript">console.log('app')</script>
</div>
</body>
</html>
Edit: Since it's been a few hours and no answers I decided to set up a repo in case anyone wants to see first-hand what the problem is.
I faced same problem, in my case it was due to some iframes in the page targetting # src url. I realized it was written several times that message in the console :
[Vue devtools message in console][1]
So, I created a new special route
Route::get('/frame', [PagesController::class, 'frame'])->name('frame');
which return an empty string like
/**
* Used for iframes to override dowloadinf twice page content
*/
public function frame() {
return "";
}
And it solved my problem. Maybe it can be the same for all ressources fetched at "#"
.
[1]: https://i.stack.imgur.com/Z55BX.png
I found out this is because of having script tags outside of a Vue component. I deleted the script tag in app.blade.php and put the ExampleComponent that comes when installing vue with laravel which has a console.log inside the mounted() method and it only gets called once.
Still, I have no idea as to why this happens. If someone could shed light into this matter that would be awesome. Maybe I'll post another question with this new insight.

Vue+laravel+apache not redirecting properly

Iḿ trying to run vue+laravel project without php artisan serve but when I acces localhost/project/public I see a blank page with this content only:
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?
family=Roboto:100,300,400,500,700,900"><link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/#mdi/font#latest/css/materialdesignicons.min.css">
</head>
<body></body>
Despite this, when I acces localhost/project/public/any I see my default not found vue page so when I click go home button I can access my entire project without problems. Anyone can help to redirect properly to / route when going to localhost/project/public.
Note: It works fine with php artisan serve and I'm trying this because I want to run my project in a ec2 instance but facing same probleme even with a virtual host to redirect to /project/public from .htacces
It's not a .htacces problem I can do the redirections as I want but when redirected to /public my vue file it's not being loaded, this is my app.js:
import Vue from 'vue';
import 'vuetify/dist/vuetify.min.css'
import Vuetify from 'vuetify'
import 'material-design-icons-iconfont/dist/material-design-icons.css'
import App from './App.vue';
import store from './store';
import router from './router';
Vue.use(Vuetify)
require('./bootstrap');
const opts = {}
import ApiService from './api/api.service';
ApiService.init();
window.Vue = require('vue');
const app = new Vue({
router,
store,
vuetify: new Vuetify(opts),
components: { App },
render: h => h(App)
}).$mount('#app');
this is my welcom.blade.php:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Administrador') }}</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Raleway:300,400,600" rel="stylesheet" type="text/css">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
<index></index>
</div>
</body>
</html>
If you're not running php artisan serve what are you running? Laravel requires the server to be running PHP in order to serve the welcome.blade.php file.

How do i integrate vue-router and laravel?

Currently i am using vue and laravel together.Vue for frontend and laravel for backend api.I am trying to use vue-router with laravel but couldnt make it work.
What i am trying to do is reach http://localhost/ec/public/#/login
app.js:
require('./bootstrap');
window.Vue = require('vue');
import Router from './routes.js'
Vue.component('example-component', require('./components/ExampleComponent.vue'));
Vue.component('login', require('./components/Login.vue'));
Vue.component('register', require('./components/Register.vue'));
const app = new Vue({
el: '#app',
router:Router
});
I have created a file in same dir app.js called routes.js:
import VueRouter from 'vue-router'
import Vue from 'vue'
import Login from './components/Login.vue'
Vue.use(VueRouter);
const router = new VueRouter({
routes:[
{
path:"/login",
component:Login
}
]
})
export default router
welcome.blade.php:
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title> site</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
</head>
<body>
<div id="app">
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
If i ad to welcome.blade.php i get component not registered error
You need to call <router-view></router-view> within your welcome.blade.php
Update
I could say that the order of the import, try to import Vue 1st then import vue-router. Otherwise you can't skip the <router-view></router-view> because it is an element of vue-router itself.

Resources