vue components wont load - laravel-5

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.

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);

vue router-view doesn't appear anything

there is no error in my code or console. But my router-view doesn't appear anything. I work with laravel 7 in this project
This is my app.js
// import Vue from 'vue';
import VueRouter from "vue-router";
import App from './components/App';
import Newsfeed from "./views/Newsfeed";
require('./bootstrap');
window.Vue = require("vue");
Vue.use(VueRouter);
const routes = [
{ path: '/', component: Newsfeed },
]
const router = new VueRouter({
routes,
mode: 'history'
})
const app = new Vue({
components: {
App
},
router: router
}).$mount('#app');
This is my App.vue
<template>
<div class="flex flex-col flex-1 h-screen overflow-y-hidden">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "App"
}
</script>
This is my Newsfeed.vue
<template>
<div class="flex flex-col items-center py-4">
Hello
</div>
</template>
<script>
export default {
name: "Newsfeed"
}
</script>
Can you help me? Thanks!

Using Typescript with Laravel and Vue.js, imports not making it to Vue components?

I'm trying to write a Vue SPA with a Laravel Backend, while also using Typescript instead of Raw Javascript. I think I'm having trouble wrapping my head around certain things, mostly surrounding typescript. Obviously I need Axios, so I attempted to import it and bind it to the Window in my bootstrap.ts file similar to the way it was done in Laravel's default bootstrap.js file.
resources/js/bootstrap.ts
import 'bootstrap';
import Axios, {AxiosStatic} from 'axios';
declare global {
// Extending the DOM Window Interface
interface Window {
axios: AxiosStatic;
}
// Extending querySelector Element
interface Element {
content: string;
}
}
declare var window: Window;
window.axios = Axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
const token: Element | null = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token')
}
That then gets imported to my app.ts file, which then sets up the Vue Router and imports the components.
resources/js/app.ts
/**
* First, we will load all of this project's Javascript utilities and other
* dependencies. Then, we will be ready to develop a robust and powerful
* application frontend using useful Laravel and JavaScript libraries.
*/
import './bootstrap';
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import App from './views/App.vue';
import Welcome from './views/Welcome.vue';
import Dashboard from './views/Dashboard.vue';
import Login from './views/Login.vue';
import Register from './views/Register.vue';
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Welcome
},
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/register',
name: 'register',
component: Register
},
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard
}
],
});
const app = new Vue({
el: '#app',
components: { App },
router,
});
However, when I attempt to use axios in my Vue components, I get the error cannot find name 'axios'. Of course I also get errors related to implicit any typings but I'm aware of why I'm getting those. Of course I also did remember to install axios from npm.
I'll post the Register.vue file here for reference, but I'm getting similar errors in any file I want to use axios in.
resources/js/views/Register.vue
<template>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card card-default">
<div class="card-header">Register</div>
<div class="card-body">
<form method="POST" action="/register">
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">Name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" v-model="name" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" v-model="email" required>
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" v-model="password" required>
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">Confirm Password</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" v-model="password_confirmation" required>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary" #click="handleSubmit">
Register
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import { Route } from 'vue-router'
#Component
export default class Register extends Vue{
name: string = ""
email: string = ""
password: string = ""
password_confirmation: string = ""
handleSubmit(e: UIEvent) {
e.preventDefault()
if (this.password === this.password_confirmation && this.password.length > 0)
{
axios.post('api/register', {
name: this.name,
email: this.email,
password: this.password,
c_password : this.password_confirmation
})
.then((response) => {
localStorage.setItem('user',response.data.success.name)
localStorage.setItem('jwt',response.data.success.token)
if (localStorage.getItem('jwt') != null){
this.$router.push('/dashboard', () => this.$router.go(0))
}
})
.catch(error => {
console.error(error);
});
} else {
this.password = ""
this.password_confirmation = ""
return alert('Passwords do not match')
}
}
beforeRouteEnter (to: Route, from: Route, next: any) {
if (localStorage.getItem('jwt')) {
return next('dashboard');
}
next();
}
}
</script>
Am I missing something obvious here? Going about this the wrong way? Here are some other miscellaneous files that may be relevant to the situation.
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.ts('resources/js/app.ts', 'public/js')
.sass('resources/sass/app.scss', 'public/css');
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"strict": true,
"module": "es2015",
"moduleResolution": "node",
"experimentalDecorators": true,
},
"include": [
"resources/js/**/*"
]
}
resources/js/typings.d.ts
declare module '*.vue' {
import Vue from 'vue';
export default Vue;
}
I did not get this to work either, what worked for me is just importing axios in every component, whenever I use axios.
import axios from 'axios';
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
const token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
No everytime you use axios somewhere else, these headers will still be set.
For instance in your Register.vue, you would just import axios from 'axios';

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

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'

Laravel blade-template import vuejs-datepicker not working

I'm trying to import the vuejs-datepicker in my template, but it is not working. I don't see any result and if I look in the console it says: Uncaught SyntaxError: Unexpected identifier. Am I doing something wrong? Is it that a import is not possible in a blade-template?
registration.blade.php:
#section('content')
...
<div class="col-lg-3 col-md-6">
<div class="form-group">
<label for="yearOfBirth">YEAR OF BIRTH*</label>
<datepicker></datepicker>
</div>
</div>
...
#endsection('content')
#endsection('content')
#section('scripts')
<script>
import Datepicker from 'vuejs-datepicker';
new Vue({
el: '#form',
data: {
name: 'Your horse',
items: []
},
methods: {
addVideo(){
this.items.push({
value: ''
});
},
deleteVideo(index){
this.items.splice(index,1);
}
},
components: {
Datepicker: Datepicker
}
});
</script>
#endsection
Found the solutions. It was in Webpack where all the scripts where in mix.scripts, while this JS-file needs to be in mix.js.

Resources