.Vue-File: Migrate structure from "template:'' to <template></template> - laravel

I try to change the structure of my .vue files (used with laravel) from the working version as seen here:
OLD foo-component.vue:
<script>
Vue.component("foo-component", {
data() {
},
props: {
},
methods: {
},
template: `
<div> Some Content Here </div>
`
});
</script>
switch this to the other structure for .vue files:
NEW: foo-component.vue:
<template>
<div> Some Content Here </div>
</template>
<script>
export default {
name: 'foo-component',
data() {
},
props: {
},
methods: {
},
}
</script>
OLD: main app.js:
Vue.component('foo-component', require('./components/foo-component.vue').default);
const app = new Vue({
el: '#app',
components: {
OtherComponents
},
data:{
},
methods: {
}
});
NEW: main app.js:
Vue.component('foo-component', require('./components/foo-component.vue').default);
const app = new Vue({
el: '#app',
components: {
OtherComponents
},
data:{
},
methods: {
}
});
But with that I get an error in the browser saying:
[Vue warn]: Unknown custom element: <foo-component> - did you register the component correctly? For recursive components, make sure to provide the "name" option.
I then added 'foo-component' to the components: {OtherComponents, foo-component} but then things got messy and the browser is saying:
Error: Module build failed: SyntaxError: X:/laragon/www/project/resources/assets/js/app.js: Unexpected token, expected , (38:35)
What am I doing wrong?
Here's the HTML/View where I call the foo-component inside the laravel blade home.blade.php:
<html>
<head>
<link type="text/css" rel="stylesheet" href="{{ mix('css/app.css') }}">
</head>
<body>
<div id="app">
<foo-component></foo-component>
</div>
<script src="{{ mix('/js/app.js') }}"></script>
</body>

You have to register your components in app.js
Vue.component('example-component', require('./components/ExampleComponent.vue').default);

The way I got it working is an update to app.js:
Vue.component('foo-component', require('./components/foo-component.vue').default);
import FooComponent from './components/foo-component.vue';
const app = new Vue({
el: '#app',
components: {
OtherComponents,
'foo-component': FooComponent
},
data:{
},
methods: {
}
});

Related

How can add a button count on my component VueJS

i starting learn VueJS and i can't add my button count on my component, i'm work with laravel !
My app.js:
window.Vue = require('vue');
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import Home from './components/HomeComponent.vue'
import Categorie from './components/CategorieComponent.vue'
let routes = [
{
path: '/',
component: Home
},
];
const app = new Vue({
mode: 'history',
el: '#app',
router: router,
data: {
message: 'Hello Vue'
}
});
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">Vous m\'avez cliqué {{ count }} fois.</button>'
});
My HomeComponent.vue:
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card-body">
<h1 class="card-tite">Bienvenue sur mon site</h1>
<button-counter></button-counter>
</div>
</div>
</div>
</div>
</template>
I add a div "app" and on this i add a <router-view><router-view> :)
My console VueJS say me :
Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.
As told in the error message, you have to register your component, before using it. Have a look on this article to read more about it.
In your example, you have to move the Vue.component('button-counter', { ... }) part in from of your app initialize. It is just another component (similar to your HomeComponent) that is defined.
Change your app.js like this:
window.Vue = require('vue');
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import Home from './components/HomeComponent.vue'
import Categorie from './components/CategorieComponent.vue'
let routes = [
{
path: '/',
component: Home
},
];
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">Vous m\'avez cliqué {{ count }} fois.</button>'
});
const app = new Vue({
mode: 'history',
el: '#app',
router: router,
data: {
message: 'Hello Vue'
}
});
... and your example should work properly.
Have a look at this running fiddle with your example.

Vue export default not working in Laravel template

I am using VueJS with Laravel, when I create Vue component and export it, it works perfect, but when I use export default in my Laravel blade in script #section it's not working.
App.js
require('./bootstrap');
window.Vue = require('vue');
// import 'swiper/dist/css/swiper.css'
import Buefy from 'buefy'
import VueAwesomeSwiper from 'vue-awesome-swiper'
import VueMatchHeights from 'vue-match-heights'
// import { swiper, swiperSlide } from 'vue-awesome-swiper'
Vue.component('featured-slider', require('./components/frontend/FeaturedSlider.vue'));
Vue.component('vehicle-offers-block', require('./components/frontend/vehicles/VehicleOffersBlock.vue'));
Vue.component('latest-news-block', require('./components/frontend/news/LatestNewsBlock.vue'));
Vue.component('finance-calculator', require('./components/frontend/FinanceCalculator.vue'));
Vue.component('latest-offers-block', require('./components/frontend/offers/LatestOffersBlock.vue'));
Vue.component('all-companies-block', require('./components/frontend/companies/AllCompaniesBlock.vue'));
Vue.component('search-vehicles-block', require('./components/frontend/SearchVehiclesBlock.vue'));
Vue.component('brand-vehicles', require('./components/frontend/offers/BrandVehicles.vue'));
Vue.component('model-topCarusel', require('./components/frontend/vehicles/ModelTopCarusel.vue'));
Vue.component('model-insideImages', require('./components/frontend/vehicles/ModelInsideImages.vue'));
Vue.component('trim-specifications', require('./components/frontend/vehicles/TrimSpecifications.vue'));
Vue.component('all-offers', require('./components/frontend/offers/AllOffers.vue'));
Vue.component('main-footer', require('./components/frontend/MainFooter.vue'));
Vue.component('featured-slider', require('./components/frontend/FeaturedSlider.vue'));
Vue.use(VueAwesomeSwiper)
Vue.use(Buefy)
Vue.use(VueMatchHeights);
const app = new Vue({
el: '#app'
});
App.blade.php
Here I created by scripts section
<body>
<!-- START NAV -->
#include ('admin.layouts.topnav')
<!-- END NAV -->
<div class="container">
<div class="columns">
<div class="column is-3">
#include ('admin.layouts.sidenav')
</div>
<div class="column is-9">
<div id="app">
#yield('content')
</div>
</div>
</div>
<script src="{{ asset('js/app.js') }}"></script>
#yield('scripts')
</div>
</body>
Larave Blade File
Here i am exporting vue js in laravel blade
#section('scripts')
<script>
export default {
data() {
return {
companyid: "",
offers: {},
SigleOfferCoverSwiper: {
slidesPerView: 1,
spaceBetween: 30,
loop: true,
pagination: {
el: '.swiper-pagination',
clickable: true
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev'
}
}
}
},
mounted () {
this.getOffers();
},
methods: {
getOffers () {
axios.get(`/api/brands/${this.companyid}/offers`).then(response => {
this.offers = response.data.offers
})
}
}
};
</script>
#endsection
Please guy help me with this.
Thanks
Seems you need to setup default for your require declaration:
Vue.component('featured-slider', require('./components/frontend/FeaturedSlider.vue').default);
Because in some cases you can face some problems with ES6 export.
Also you can use module.exports = {}.

Laravel, Vue component template not show?

Sorry, my English is so bad!
File: app.js
window.auth_id = 0;
Vue.component('block-header-user-control', require('./HeaderComponent.vue'));
new Vue({
el: '#application'
});
File HeaderComponent.vue
<template lang="html">
<header-guest v-if="!auth"></header-guest>
<header-auth v-else></header-auth>
</template>
<script>
import HeaderGuest from './HeaderUserGuest.vue';
import HeaderAuth from './HeaderUserAuth.vue';
export default {
data: function () {
return {
auth: window.auth_id
}
},
components: {
'header-guest': HeaderGuest,
'header-auth': HeaderAuth,
},
methods: {},
}
</script>
File: HeaderUserGuest.vue
<script>
export default {
template: '#header-user-auth', // Not working,
// template: `<div>cascaaSA</div>`, // working
data() {
return {}
},
mounted() {
console.log('Created Guest');
},
}
</script>
File: HeaderUserAuth.vue
<script>
export default {
template: '#header-user-auth',
name: 'header-auth',
data() {
return {}
},
created() {
console.log('Created Auth');
},
}
</script>
File: index.blade.php
<div id="application">
<script type="text/x-template" id="header-user-guest">
Guest
</script>
<script type="text/x-template" id="header-user-auth">
Logged
</script>
<block-header-user-control></block-header-user-control>
</div>
"Created Guest" is displayed in browser console, but the "block-header-user-control" menu does not display "Guest".
Please help me. SPECIAL THANKS!!
====================
Thank all! It worked with html. Text not working
<div id="application">
<script type="text/x-template" id="header-user-guest">
<div>Guest</div>
</script>
<script type="text/x-template" id="header-user-auth">
<div>Logged</div>
</script>
<block-header-user-control></block-header-user-control>
</div>
You might need to move your templates outside of the scope of the application - move them below #application.

laravel 5 vue setup unclear

I've tried about everything now but I can't get vue.js to work on Laravel, there doesn't seem to be anything concrete around that says put x in file y to get it working.
I've tried about everything with npm, composer but i can't even get a basic example to work. It's very unclear to me what I need and where it needs to go.
I am using blade to extend from an app.layout view but it's unclear wether i need to add code to assets/js/app.js or just use script src="" tags in my default app layout.
app.js
require('./bootstrap');
window.Vue = require('vue');
Vue.component('example', require('./components/Example.vue'));
const app = new Vue({
el: '#app'
});
var app5 = new Vue({
el: '#app-5',
data: {
message: 'Hello Vue.js!'
} ,
methods: {
reverseMessage: function () {
this.message = this.message.split('').reverse().join('')
}
}
})
app.layout.blade.php
<script src="{{asset('/js/app.js')}}"/></script>
..some more html
<body id="app">
<div id="app-5">
<p>#{{ message }}</p>
<button v-on:click="reverseMessage">Reverse Message</button>
</div>
</body>
..more html
why you define two Vue const?
this part of js code is no needed:
const app = new Vue({
el: '#app'
});
remove that line and test it :
require('./bootstrap');
window.Vue = require('vue');
Vue.component('example', require('./components/Example.vue'));
var app5 = new Vue({
el: '#app-5',
data: {
message: 'Hello Vue.js!'
} ,
methods: {
reverseMessage: function () {
this.message = this.message.split('').reverse().join('')
}
}
})
but remmember your vuejs work should be beetween:
<div id="app-5"> vuejs codes should be run here </div>
Don't forget running npm run watch or npm run dev to compile
if you have error and problem with this way you can skip to second way
Second Way:
create vue-script.js file in public/js/ directory
vue-script.js:
var app5 = new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
} ,
methods: {
reverseMessage: function () {
this.message = this.message.split('').reverse().join('')
}
}
})
create sample.blade.php file in resources/views/ directory
sample.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>test page</title>
</head>
<body>
<div id="app">
#{{ message }}
<button v-on:click="reverseMessage">Reverse Message</button>
</div>
<script src="https://unpkg.com/vue"></script>
<script src="{{ asset('js/vue-script.js') }}"></script>
</body>
</html>
then in routes/web.php:
Route::get('testvue', function() {
return view('sample');
});
and go to url : /testvue in your browser

Vue & Laravel: Access and use eventHub

In resources/assets/js/app.js I have created eventHub Vue instance:
require('./bootstrap');
var eventHub = new Vue();
Vue.component('todos-list', require('./components/todos/TodoList.vue'));
Vue.component('todos-add', require('./components/todos/TodoAdd.vue'));
const app = new Vue({
el: '#app'
});
How can I use it in components that are created in separate .vue files?
For example, I also have two components:
todos-list located in /components/todos/TodoList.vue, which is used to fetch the data from server-side using vue-resource:
<template id="todos-list-template">
<div>
<ul v-if="todos.length > 0">
<li v-for="todo in todos">
{{ todo.title }}
</li>
</ul>
<p v-else>You don't hanve any Todos.</p>
</div>
</template>
<script>
export default {
template: '#todos-list-template',
data() {
return {
todos: {}
}
},
mounted() {
this.$http.get('api/vue/todos').then(function(response) {
this.todos = response.data;
});
},
methods: {
handleAddedTodo: function(new_todo) {
this.todos.push(new_todo);
}
},
created: function() {
eventHub.$on('add', this.handleAddedTodo);
},
destroyed: function() {
eventHub.$off('add', this.handleAddedTodo);
}
}
</script>
todos-add located in /components/todos/TodoAdd.vue which is used to add (save) the new 'todo' using vue-resource:
<template id="todos-add-template">
<div>
<form v-on:submit.prevent="addNewTodo()">
<div class="form-group">
<input v-model="newTodo.title" class="form-control" placeholder="Add a new Todo">
</div>
<div class="form-group">
<button>Add Todo</button>
</div>
</form>
</div>
</template>
<script>
export default {
template: '#todos-add-template',
data() {
return {
newTodo: { id: null, title: this.title, completed: false }
}
},
methods: {
addNewTodo() {
this.$http.post('api/vue/todos', { title: this.newTodo.title }).then(function(response) {
if (response.status == 201) {
eventHub.$emit('add', response.data);
this.newTodo = { id: null, title: this.title, completed: false }
}
}, function(response) {
console.log(response.status + ' - '+ response.statusText);
})
}
}
}
</script>
When I add (save) new 'todo' using the todos-add component (TodoAdd.vue) - I want to update data in todos-list component. If I understood well the documentation - for component communication we need to use centralized event hub. And that's what I tried - but I am getting the following error:
eventHub is not defined
I guess because it is defined in app.js, but how can I use in components that are created in separate .vue files?
You are getting this error because eventHub is actually not defined where you are using it. You have to export this from app.js and import in TodoAdd.vue.
in app.js:
var eventHub = new Vue()
exports.eventHub = eventHub
Add this code in TodoAdd.vue:
<script>
import eventHub from '/path/of/app'
export default {
template: '#todos-list-template',
This should make eventHub availble in TodoAdd.vue.
Edited
As the comment suggests, you may consider using vuex, as you have data whcih is being used across components, and going forward I see chances of getting it more complex, more event handlers and event listerners, which can quickly become a nightmare to manage.
var eventHub = new Vue()
You are getting this error because eventHub is actually not defined where you are using it. You have to export this from app.js file. Use this one
window.eventHub = new Vue()

Resources