I receive error after reboot page in Vue3 - vuejs3

Delab some code changes Vue3-Vite.
I receive error after reboot page in Vue3.
Uncaught ReferenceError: Cannot access 'router' before initialization
router\index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
]
App.vue
<router-link
to="/"
>
<button
type="button"
class="btn btn-outline-primary mx-4"
>
Home
</button>
</router-link>

router\index.js
import { createWebHistory, createRouter } from "vue-router";
const history = createWebHistory();
const routes = [/* Routes*/];
const router = createRouter({ history, routes });
export default router;
add router in main.js
import router from "./router";
createApp(App).use(router).mount("#app");

At no time does it see how you use a router in your app when it is mounted.
In all cases you should do something like
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import { createApp} from 'vue';
const routes = createRouter([
{
path: '/',
name: 'Home',
component: Home
},
)]
const app = createApp(Home);
app.use(routes);

Related

How to show login page outside the layout using vue js 3?

I want to show login page outside the layout but unfortuntly i see the sidebar and header on login page sidebar and header should not be on login page please help me how can i resolve that thank u ?
App.vue
<script setup>
import { RouterLink, RouterView } from 'vue-router'
import Layout from './components/Layouts/Layout.vue'
</script>
<template>
<div id="app">
<Layout></Layout>
</div>
<RouterView />
</template>
<script>
export default {
name: 'App',
components: {
Layout,
}
}
</script>
router\index.js
import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'login',
component: Login
},
{
path: '/dashboard',
name: 'dashboard',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/DashBoard.vue')
},
]
})
export default router
Use conditional rendering to hide/show elements based on the current route
<Layout v-if="route.path !== '/'"></Layout>
<script setup>
import { RouterLink, RouterView, useRoute } from 'vue-router'
import Layout from './components/Layouts/Layout.vue'
const route = useRoute();
</script>
Also, not sure why you have two script tags. You don't need to register components with the Composition API (script setup), so you can/should remove the second script

How to use multiple Vuex Stores with Inertia and Laravel 9?

Below is how I registered one Vuex store in app.js.
import './bootstrap';
import '../css/app.css';
import { createApp, h } from 'vue';
import { createInertiaApp } from '#inertiajs/inertia-vue3';
import { InertiaProgress } from '#inertiajs/progress';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { ZiggyVue } from '../../vendor/tightenco/ziggy/dist/vue.m';
import store from '#/Pages/Users/Store'; // Vuex Store, Users module
const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
setup({ el, app, props, plugin }) {
return createApp({ render: () => h(app, props) })
.use(plugin)
.use(ZiggyVue, Ziggy)
.use(store)
.mount(el);
},
});
InertiaProgress.init({ color: '#4B5563' });
Below is the Pages/Users/Store/index.js.
import { createStore } from "vuex";
export const store = createStore({
state: {
count: 123,
name: "My name"
}
});
export default store;
Below is how I use the Vuex store state in a module's component Pages/Users/Index.vue.
<script>
import { mapState } from "vuex";
export default {
computed: mapState({
count: state => state.count,
name: state => state.name,
email() {
return "hello#world.com";
}
})
};
</script>
<template>
<div>
{{ email }} {{ count }} {{ name }}
</div>
</template>
If I have many pages and many modules such as Users, Chirps, Customers, each module for each page. How can I load and use only the Vuex Store of that module when Inertia renders that Vue component of an individual page?

Laravel API route doesnt work on vue3 vue-router

Hey everyone laravel 9 vue 3 and vue-router the problem is that localhost:8000/api/admin/login is not available. Transition opens non-existent vue components page Can you suggest how to exclude api prefix from vue router.
Backend: Laravel 9
PHP: 8.0
Fronted: Vue3,axios, vue-routera
web.php
Route::get('{any?}', function () {
return view('welcome');
})->where('any', '.*');
api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\Admin\UserController;
Route::any('login', [UserController::class, 'login']);
Route::any('register', [UserController::class, 'register']);
Route::group(['middleware' => 'auth:api'], function () {
Route::get('logout', [UserController::class, 'logout']);
Route::get('user', [UserController::class, 'user']);
});
app.js
import {createApp} from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import axios from 'axios'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(ElementPlus)
app.use(router, axios)
app.config.globalProperties.$axios = axios
app.mount("#app")
router.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from './components/Main/HomeComponent.vue';
import Login from './components/Main/LoginComponent.vue';
import Dashboard from './components/Main/DashboardComponent.vue';
const routes = [
{
path: '/',
name: 'home',
component: Home,
meta: {
requiresAuth: false,
title: 'Home',
}
},
{
path: '/login',
name: 'login',
component: Login,
meta: {
requiresAuth: false,
title: 'Login',
}
},
{
path: '/dashboard',
name: 'dashboard',
component: Dashboard,
meta: {
requiresAuth: true,
title: 'Dashboard',
}
}
]
const router = createRouter({
history: createWebHistory(),
mode: 'history',
routes,
linkExactActiveClass: 'active'
});
// eslint-disable-next-line no-unused-vars
router.beforeEach((to, from) => {
document.title = to.meta.title;
if (to.meta.requiresAuth === true && !this.$store.authenticated) {
return this.$router.push('/login');
}
})
export default router
In the end, calling api route.php worked correctly

Not able to fetch url params in vue js

Hi I am trying to fetch the value for "customerID" and "iot" in MyIOT.vue. When I enter the url http://localhost:8080/5/345435 it gives me an empty value for params. I tried both ways using routing and props. None of them is working. Not sure where I am getting it wro
main.js
import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import App from './App.vue'
import MyIot from './components/MyIOT.vue'
//import router from './router/index.js'
const routes = [
// {
// path: '/',
// redirect: '/:customerID/:iot'
// },
{
path: '/:customerID/:iot',
component: MyIot,
//props: true,
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
const app = createApp(App).use(router);
app.mount('#app');
App.vue
<template>
<MyIot />
</template>
<script>
import MyIot from './components/MyIOT.vue'
//import axios from "axios";
export default {
name: "App",
components: {
MyIot,
},
};
</script>
components/MyIOT.vue
<template>
<div>customer id is: {{customerID}} and iot is : {{iot}}
</div>
</template>
<script>
import { useRoute } from 'vue-router'
export default {
name: 'MyIot',
//props: ['customerID', 'iot'],
setup() {
const route = useRoute();
console.log(route.params);
}
}
</script>

router-link won't load page

Can't find what I am doing wrong. If I type the url on the browser the page does load, but the links from the navbar do nothing. I am trying three different ways to use router-link, but makes no differences. It just won't render the page via link. No errors on the console. On the vue devtools the routing displays the correct path.
App.vue:
<template>
<nav class="navbar">
<router-link :to="{ path: '/' }">Home</router-link>
<router-link :to="{name:'TheDashboard'}"> Dashboard</router-link>
<router-link to="/games">Games</router-link>
</nav>
<router-view></router-view>
</template>
router/index.js:
import { createRouter, createWebHistory } from 'vue-router'
import TheHomePage from '#/pages/TheHomePage'
import TheDashboard from '#/pages/TheDashboard'
const routes = [
{
path: '/',
name: 'TheHomePage',
component: TheHomePage
},
{
path: '/dashboard',
name: 'TheDashboard',
component: TheDashboard
},
{
path: '/games',
name: 'TheGames',
component: () => import(/*webpackChunkName: "games" */ '#/pages/TheGames.vue'),
props: true
},
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
main.js:
import { createApp } from 'vue'
import App from '#/App.vue'
import router from '#/router'
import store from '#/store'
const prototype = createApp(App)
prototype.use(router)
prototype.use(store)
prototype.mount('#app')
In the end this was a bug caused by Vue devtools. I removed previous versions and updated to latest, and it is now working. Nothing wrong with the code. I thought I might as well leave the code here, since it might be helpful for other people.
your code seems optimal to me. However, you can use the beforeEach and afterEach hooks to help you to debug your App.
you can read about them here
do something like:
//router/index.js
//...
//const router = ...
router.afterEach((to, from, failure) => {
console.log('to: ', to);
console.log('from: ', from);
if (isNavigationFailure(failure)) {
console.log('failed navigation', failure)
}
});
export router;

Resources