Laravel 6 + Vue.js Failed to mount component: template or render function not defined - laravel

Perhaps someone could help me? I'm trying to create a little chat app from here and I am have trouble displaying the Vue components.
The dev tools console gives me:
Failed to mount component: template or render function not defined.
I am using Laravel 6
Appreciate any help on this one! thanks :)
I have tried deleting the node_modules folder and rebuilding, after adding .default - with no luck.
app.js
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('chat-messages', require('./components/ChatMessages.vue').default);
Vue.component('chat-form', require('./components/ChatForm.vue').default);
import Vue from 'vue'
const app = new Vue({
el: '#app',
data: {
messages: []
},
created() {
this.fetchMessages();
Echo.private('chat')
.listen('MessageSent', (e) => {
this.messages.push({
message: e.message.message,
user: e.user
});
});
},
methods: {
fetchMessages() {
axios.get('/messages').then(response => {
this.messages = response.data;
});
},
addMessage(message) {
this.messages.push(message);
axios.post('/messages', message).then(response => {
console.log(response.data);
});
}
}
});
and my two components:
ChatForm.vue
<template>
<div class="input-group">
<input id="btn-input" type="text" name="message" class="form-control input-sm" placeholder="Type your message here..." v-model="newMessage" #keyup.enter="sendMessage">
<span class="input-group-btn">
<button class="btn btn-primary btn-sm" id="btn-chat" #click="sendMessage">
Send
</button>
</span>
</div>
</template>
<script>
export default {
props: ['user'],
data() {
return {
newMessage: ''
}
},
methods: {
sendMessage() {
this.$emit('messagesent', {
user: this.user,
message: this.newMessage
});
this.newMessage = ''
}
}
}
</script>
ChatMessage.vue
<template>
<ul class="chat">
<li class="left clearfix" v-for="message in messages" v-bind:key="message">
<div class="chat-body clearfix">
<div class="header">
<strong class="primary-font">
{{ message.user.name }}
</strong>
</div>
<p>
{{ message.message }}
</p>
</div>
</li>
</ul>
</template>
<script>
export default {
props: ['messages']
};
</script>

This might help you to solve your problem, if not just tell me to find new solution. first remove this in your app.js
const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))
Next, remove also this code, you already imported vue twice.
import Vue from 'vue'

Related

Unknown custom element: <app-home> - did you register the component correctly? For recursive components, make sure to provide the "name" option

I have this problem but i try some solutions in web but and i can't resolve it: Unknown custom element:
- did you register the component correctly? For recursive components, make sure to provide the "name" option.
The problem appears to be in those fils :
Please I need help as soon as possible
routes.js:
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../components/Home.vue";
import PostDetails from "../components/PostDetails.vue";
Vue.use(VueRouter);
const routes = [{
path: "/",
component: Home,
name: "Home"
},
{
path: "/post/:slug",
component: PostDetails,
name: "postDetails"
}
];
const router = new VueRouter({
routes: routes,
hashbang: false,
mode: "history"
});
export default router;
app.js:
import Vue from "vue";
import VueRouter from "vue-router";
require('./bootstrap');
window.Vue = require('vue');
Vue.component(key.split('/').pop().split('.')[0], files(key).default))
Vue.component('app-home', require('./AppHome.vue'));
import router from "./routes/routes.js";
const app = new Vue({
el: '#app',
vuetify,
render: h => h(App),
router: router,
});
AppHome.vue:
<template>
<div>
<router-view></router-view>
</div>
</template>
<script>
export default {
};
</script>
Home.vue:
<template>
<div class="container">
<div class="row my-4">
<div class="col-md-8">
<div class="card">
<div class="card-header">Articles</div>
<div
class="card-body"
:key="index"
v-for="(post, index) in posts.data"
>
<div class="media">
<img
:src="post.photo"
class="rounded img-fluid mr-2 shadow-sm"
alt=""
srcset=""
/>
<div class="media-body text-justify">
<router-link :to="post.path">
<h3>{{ index }}:{{ post.title }}</h3>
</router-link>
<p>
<span class="textdefaut">
{{ post.user.name }}
</span>
<span class="text-danger">
{{ post.added }}
</span>
</p>
<p class="lead text-justify">
{{ post.body.substr(0, 200) }}...
</p>
<hr />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
posts: {},
};
},
created() {
this.getPosts();
},
methods: {
getPosts() {
axios
.get("/api/posts")
.then((response) => {
console.log(response.data);
this.posts = response.data;
})
.catch((err) => console.log(err));
},
},
};
</script>
Post Details:
<template>
<div>
Posts details , This shows that the route is really working!!
<router-link to="/Home"><a>Back to the root</a></router-link>
</div>
</telpmate>
<script>
export default {
data () {
return {
message: 'Hoera!!!!'
};
}
};
</script>
If all of your Vuejs components (including AppHome.vue) are in /resources/js/components directory, you must change:
Vue.component('app-home', require('./AppHome.vue'));
by
Vue.component('app-home', require('./components/AppHome.vue'));
...in your app.js
Try to append .default option:
Vue.component('app-home', require('./components/AppHome.vue').default);

Uncaught TypeError: axios.ad is not a function in vue script

I'm having this error with my vue script, this are the files i'm using
Can't find the error reported with the axios.ad (favoriteAd.vue).
It's basically a favourite feature using:
https://scotch.io/tutorials/implement-a-favoriting-feature-using-laravel-and-vue-js#comments-section
(replacing post with ad)
app.js
require('./bootstrap');
window.Vue = require('vue');
Vue.component('favorite', require('./components/FavoriteAd.vue'));
const app = new Vue({
el: '#favorite'
});
favoriteAd.vue
<template>
<span>
<a href="#" v-if="isFavorited" #click.prevent="unFavorite(ad)">
<i class="fa fa-heart"></i>
</a>
<a href="#" v-else #click.prevent="favorite(ad)">
<i class="fa fa-heart-o"></i>
</a>
</span>
</template>
<script>
export default {
props: ['ad', 'favorited'],
data: function() {
return {
isFavorited: '',
}
},
mounted() {
this.isFavorited = this.isFavorite ? true : false;
},
computed: {
isFavorite() {
return this.favorited;
},
},
methods: {
favorite(ad) {
console.log(ad);
axios.ad('/favorite/'+ad) // this is the error line
.then(response => this.isFavorited = true)
.catch(response => console.log(response.data));
},
unFavorite(ad) {
axios.ad('/unfavorite/'+ad)
.then(response => this.isFavorited = false)
.catch(response => console.log(response.data));
}
}
}
view
#if (Auth::check())
<favorite
:ad={{ $aviso->id }}
:favorited={{ $aviso->favorited() ? 'true' : 'false' }}
></favorite>
#endif
You never included axios in your app. Try npm install axios then require('./axios') on the app.js file. Also, according to the axios reference manual, there's no method named ad.

vue components wont load

I try to work with vuejs in laravel, I installed npm vue-router vue-axios but when i try to load my page i get console error like: ReferenceError: CreateCategory is not defined and empty page.
here is my app.js:
require('./bootstrap');
window.Vue = require('vue');
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import VueAxios from 'vue-axios';
import axios from 'axios';
Vue.use(VueAxios, axios);
import App from './App.vue';
Vue.component('CreateCategory', require('./components/CreateCategory.vue'));
Vue.component('DisplayCategory', require('./components/DisplayCategory.vue'));
Vue.component('EditCategory', require('./components/EditCategory.vue'));
const routes = [
{
name: 'CreateCategory',
path: '/categories/create',
component: CreateCategory
},
{
name: 'DisplayCategory',
path: '/',
component: DisplayCategory
},
{
name: 'EditCategory',
path: '/edit/:id',
component: EditCategory
}
];
const router = new VueRouter({ mode: 'history', routes: routes});
new Vue(Vue.util.extend({ router }, App)).$mount('#app');
// const app = new Vue({
// router,
// render: h => h(App)
// });
// const app = new Vue({
// el: '#app'
// });
PS: I read articles about component in router and I already tried with .default that won't work neither they only good of that was i didn't get console error.
UPDATE
my CreateCategory.vue component:
<template>
<div>
<h1>Create A Category</h1>
<form v-on:submit.prevent="addCategory">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Category Title:</label>
<input type="text" class="form-control" v-model="category.title">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Category Status:</label>
<input type="text" class="form-control col-md-6" v-model="category.status" />
</div>
</div>
</div><br />
<div class="form-group">
<button class="btn btn-primary">Add Category</button>
</div>
</form>
</div>
</template>
<script>
export default {
data(){
return{
category:{}
}
},
methods: {
addCategory(){
let uri = 'http://localhost/vuetjd/public/categories';
this.axios.post(uri, this.category).then((response) => {
this.$router.push({title: 'DisplayCategory'})
})
}
}
}
</script>
CreateCategory.vue is a Single File Component.
In there, you must have a export default {}, where {} is actually the Component Object.
What you have to do, is that, you need to import the CreateCategory.vue and then assign it, like so:
import CreateCategory from './components/CreateCategory.vue';
const routes = [
{
name: 'CreateCategory',
path: '/categories/create',
component: CreateCategory
}
];
now this will work.
you have to do the same for DisplayCategory and EditCategory.
I found what is the issue, I'm suppose to run php artisan serve to be able to see my data. if just open my url i'll get blanck page but with serve i get my data as well.

Laravel/Vue.js issues

I need help with my code please. I can't figure it out. I'm getting a "TypeError: this.$http is undefined" and it's driving me insane. I trace it to $http, but I have no idea how to fix it. I've just finished my Laravel course, but Vue.js is new to me. Here's is my code:
<template>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-body">
<textarea rows="3" class="form-control" v-model="content"></textarea>
<br>
<button class="btn btn-success pull-right" :disabled="not_working" #click="create_post()">
Create a post
</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
},
data() {
return {
content: '',
not_working: true
}
},
methods: {
create_post() {
this.$http.post('/create/post', { content: this.content })
.then((resp) => {
this.content = ''
noty({
type: 'success',
layout: 'bottomLeft',
text: 'Your post has been published !'
})
console.log(resp)
})
}
},
watch: {
content() {
if(this.content.length > 0)
this.not_working = false
else
this.not_working = true
}
}
}
</script>
I think you have a error in submitting the post request.
you need to learn about axios.
Try this example.
axios.post('/create/post', this.content).then((response) => {
// do something
})
npm install axios --save
Add Axios to your Vue.js project, you have to import it:
<script>
import axios from 'axios';
export default {
data() {
return {
posts: [],
errors: []
}
},
created() {
let payload={
content:this.content
}
axios.post('/create/post',payload)
.then(response => {
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>

Getting error "Failed to mount component: template or render function not defined." while using js file as Vue component

I'm using Vue in Laravel 5.3. I have already worked with Laravel 5.2. But Laravel 5.3 and Vue.js is new for me. So I'm playing with these pair. I have completed Laravel Passport tutorial successfully. Now what I want to do is put my html template in blade file and js code in Vue component. But I'm getting this error:
[Vue warn]: Failed to mount component: template or render function not defined. (found in component )
So I can't understand reason of this error as I'm new in Vue.js. If any one knows answer, it will be appreciated. Here is my code.
Blade file
<body>
<div id="app">
<tasks></tasks>
</div>
<template id="tasks-template">
<ul class="list-group">
<li class="list-group-item" v-for="task in list">
#{{task.body}}
</li>
</ul>
</template>
<script src="/js/app.js"></script>
</body>
/resources/assets/js/app.js
require('./bootstrap');
Vue.component('tasks', require('./components/Tasks'));
const app = new Vue({
el: '#app'
});
/resources/assets/js/components/Tasks.js
export default {
template: '#tasks-template',
data: function () {
return {
list: ''
};
},
created: function() {
this.$http.get('/api/tasks').then((response) => {
this.list = response.body;
}, (response) => {
alert(0);
});
}
}
UPDATE
Blade file
<body>
<div id="app">
<tasks></tasks>
</div>
</body>
/resources/assets/js/components/Tasks.js
template: require('../components/tasks-template.html'),
instead of
template: '#tasks-template'
/resources/assets/js/components/tasks-template.html
<ul class="list-group">
<li class="list-group-item" v-for="task in list">
{{task.body}}
</li>
</ul>
But now getting this error.
Uncaught Error: Module parse failed: /var/www/html/casesync/resources/assets/js/components/tasks-template.html Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
|
|
| #{{task.body}}
Lets say you have your template file as
/* resources/assets/js/components/tasks.template.html */
<div class="tasks-component component">
<ul class="list-group">
<li class="list-group-item" v-for="task in list">
{{task.body}}
</li>
</ul>
</div>
Then the Tasks.js would be
/* resources/assets/js/components/Tasks.js */
export default {
template: require('./tasks.template.html'),
data: function () {
return {
list: ''
};
},
created: function() {
this.$http.get('/api/tasks').then((response) => {
this.list = response.body;
}, (response) => {
alert(0);
});
}
}
The you can have your app.js as
/* app.js */
require('./bootstrap');
Vue.component('tasks', require('./components/Tasks').default);
const app = new Vue({
//el: '#app'
}).$mount('#app');
//your main index.php or entry point could be
<body>
<div id="app">
<tasks></tasks>
</div>
</body>
UPDATE
For the default/out-of-box webpack configuration to work on Laravel5.3, you will need to pull in html-loader through npm
npm install html-loader --save-dev
Then in the gulpfile.js - specify html-loader to be used for .html files.
const elixir = require('laravel-elixir');
require('laravel-elixir-vue-2');
const config = {
module: {
loaders:[
{
test: /\.html$/,
loader: 'html'
}
]
}
};
elixir((mix) => {
mix.sass('app.scss')
.webpack('app.js', null, null, config);
});
Finally you can register global components in your main/entry file app.js as
Vue.component('test-component', require('./test-component').default);
/* Or using ES2015 import */
import TestComponent from './test-component';
Vue.component('test-component', TestComponent);
I got help from #Alfa here
It should be require('./components/Example.vue').default. Since v13, vue-loader exports the component as the default key, which still works the same when using import, but requires the above when using require.
I had the same problem importing a vue component.
You have to change
Vue.component('tasks', require('./components/Tasks'));
change it to
Vue.component('tasks', require('./components/Tasks').default);

Resources