Trouble getting data from root Vue instance with vue-router - javascript

I load all of my data in the root Vue instance and im trying to access them in my router.
How can I access the data in my root instance within my router? All the this.a.app or this.app answers i found online weren’t the solution.
Router.js:
import Vue from 'vue'
import Router from 'vue-router'
import Login from '../components/login'
import Container from '../components/container'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [{
path: '/login',
name: 'Login',
component: Login,
props: { test: **<data from my Vue root instance>** }
},
{
path: '/products',
name: 'Container',
component: Container,
children: [{
path: 'flavor',
component: Login
},
{
path: 'storage',
component: Login
},
{
path: 'network',
component: Login
}
]
}
]
})
Main.js:
import router from './router’
var vm = new Vue({
el: ‘#app’,
router,
template: ‘’,
components: {
App
},
data() {
return {
modal: ‘’

I would avoid sharing the data using the router instance.
I personally like to have a store file, which contains data I want to share between my components.
export default {
state: {
counter: 0
}
}
And in your component you can import the file:
import store from '../store'
export default {
data () {
return {
sharedState: store.state
}
}
}
Changes to sharedState will also be passed to other components.
Source: https://skyronic.com/2016/01/03/vuex-basics-tutorial / Solution 2

Related

Npm run generate not generating routes

I am using vue-router in a nuxt project and when i run npm run generate it generates everything except my pages. I think it has got something to do with the router because before using vue router i had no problems with generating the pages Here is my router:
router.js
import Vue from 'vue'
import Router from "vue-router"
import Home from '../debonkelaer/pages/index.vue'
import actueel from '../debonkelaer/pages/actueel.vue'
import impressies from '../debonkelaer/pages/impressies.vue'
import reglement from '../debonkelaer/pages/reglement.vue'
import reserveren from '../debonkelaer/pages/reserveren.vue'
import tarieven from '../debonkelaer/pages/Tarieven.vue'
import ingelogd from '../debonkelaer/pages/ingelogd.vue'
import firebase from 'firebase/app'
import 'firebase/auth'
Vue.use(Router);
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/actueel',
name: 'Actueel',
component: actueel
},
{
path: '/impressies',
name: 'Impressies',
component: impressies
},
{
path: '/reserveren',
name: 'Reserveren',
component: reserveren
},
{
path: '/tarieven',
name: 'Tarieven',
component: tarieven
},
{
path: '/reglement',
name: 'Reglement',
component: reglement
},
{
path: '/ingelogd',
name: 'Ingelogd',
component: ingelogd,
}
]
const router = new Router({
mode: 'history',
base: '/',
routes
})
export function createRouter() {
return router
};```
If you need any additional code please reply.
When you're working with nuxt.js all routes are automatically generating from all your files in your pagesdirectory. That means you don't need to manually declare every route!
Be sure to check out the official documentation for nuxt.js: Automatic Routing
To check for auth you should use middleware.
If you only need it for one specific route/component, you can use something like the following code in your component's exported function
middleware({ redirect }) {
// If the user is not authenticated
const authenticated = YOUR_AUTH
if (!authenticated) {
return redirect('/login')
}
}

Trying to make a VueJS API call with axios to get json in a component named prijzen

I am new to Vue and am trying to load in json data from a REST API called JSON placeholder. I get the error:
"Uncaught ReferenceError: Prijzen is not defined
at eval (cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/layout/Prijzen.vue?vue&type=script&lang=js&:16)
at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/layout/Prijzen.vue?"
So after i got this i tried looking at index.js but prijzen is added there.. the code looks like this:
import Vue from 'vue'
import Router from 'vue-router'
// Containers
const TheContainer = () => import('#/containers/TheContainer')
// Views
const Dashboard = () => import('#/views/Dashboard')
const Prijzen = () => import('#/views/layout/Prijzen')
const Login = () => import('#/views/layout/Login')
Vue.use(Router)
export default new Router({
mode: 'hash', // https://router.vuejs.org/api/#mode
linkActiveClass: 'open active',
scrollBehavior: () => ({ y: 0 }),
routes: [
{
path: '/',
redirect: '/dashboard',
name: 'Home',
component: TheContainer,
children: [
{
path: 'dashboard',
name: 'Dashboard',
component: Dashboard
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/layout/prijzen',
name: 'Prijzen',
component: Prijzen
}
]
},
]
})
So prijzen is fine here. At least it looks fine to me. This is how the prijzen component looks:
<template>
<div id="Prijzen">
{{ prijs }}
</div>
</template>
<script>
import axios from 'axios';
import PrijsItem from './PrijsItem.vue';
export default {
name: 'Prijzen',
components: {
PrijsItem
},
props: ["PrijsItem"]
}
</script>
I have used {{ prijs }} in the template and in my main.js file it is being mentioned with my axios get request as you can see here:
import 'core-js/stable'
import Vue from 'vue'
import CoreuiVue from '#coreui/vue/src'
import App from './App'
import router from './router/index'
import { iconsSet as icons } from './assets/icons/icons.js'
import store from './store'
Vue.use(CoreuiVue)
new Vue({
el: '#app',
router,
store,
//CIcon component documentation: https://coreui.io/vue/docs/components/icon
icons,
template: '<App/>',
components: {
App,
Prijzen
},
new:({
let: '#Prijzen',
data () {
return {
prijs: null
}
},
mounted () {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then(response => (this.prijs = response))
}
})
})
Is the Prijzen.vue file definitely in the views/layout directory? That error looks like it might be caused by not being able to find the file where you've told it to look.
A different issue:
{{ prijs }}
Is in the template, but prijs is not defined. Also PrijsItem component has been imported but not used which will sometimes throw linting errors.

vue-router showing blank page when built

I'm asking for help. I use vuejs to make my application. Everything works perfectly. But I do the npm run build, I extract the dist folder and I open index.html, I have a blank page, and when I look in the console, I have no errors.
main.js
import Vue from "vue";
import Vuex from "vuex";
import router from "./router";
import App from "./App.vue";
import vuetify from "./plugins/vuetify";
import store from "./store";
import {
ValidationObserver,
ValidationProvider,
extend,
localize
} from "vee-validate";
import fr from "vee-validate/dist/locale/fr.json";
import * as rules from "vee-validate/dist/rules";
// install rules and localization
Object.keys(rules).forEach(rule => {
extend(rule, rules[rule]);
});
localize("fr", fr);
// Install components globally
Vue.component("ValidationObserver", ValidationObserver);
Vue.component("ValidationProvider", ValidationProvider);
Vue.config.productionTip = false;
//load vue-moment
Vue.use(require("vue-moment"));
//Load vuex
Vue.use(Vuex);
//Load vueRouter
new Vue({
router,
vuetify,
store,
render: h => h(App)
}).$mount("#app");
router/index.js
import Vue from "vue";
import VueRouter from "vue-router";
import Professeur from "../components/Professeur";
import Matiere from "../components/Matiere";
import Dashboard from "../components/Dashboard";
import Filiere from "../components/Filiere";
import Salle from "../components/Salle";
import Shedule from "../components/Shedule";
import SheduleLine from "../components/SheduleLine";
import Login from "../components/Login";
import Home from "../components/Home";
Vue.config.productionTip = false;
Vue.use(VueRouter);
const router = new VueRouter({
mode: "history",
routes: [
{
path: "/dashboard",
name: "dashboard",
component: Dashboard,
meta: {
requiresAuth: true
},
children: [
{
path: "personnel/professeurs",
name: "p_professeur",
component: Professeur
},
{
path: "",
name: "home",
component: Home
}
]
},
{
path: "/login",
name: "login",
component: Login,
meta: {
guest: true
}
}
]
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
let user = JSON.parse(localStorage.getItem("_GET_TOKEN"));
if (!user && !user.token) {
next({
name: "login"
});
} else {
next();
}
} else {
next();
}
});
export default router;
App.vue
<template>
<v-app>
<router-view/>
</v-app>
</template>
<script>
export default {
name: 'app',
}
</script>
Once I compile, I have no errors but a blank page.
Thanks for any help. I tried without the router view, I manage to launch the index.html once compiled for production and I have a rendering.
You're using history mode for your router, which means you'll access your pages with paths like /login or /dashboard or /dashboard/personnel/professeurs, which are the only routes you declared.
/ or /index.html does not display anything because the router doesn't know what they are.
However, in order to have history mode working, you cannot just have a static server. The server has to know that a request to /dashboard should return the index.html file.
If you used VueCLI, the docs here might be helpful:
If you are using Vue Router in history mode, a simple static file server will fail. For example, if you used Vue Router with a route for /todos/42, the dev server has been configured to respond to localhost:3000/todos/42 properly, but a simple static server serving a production build will respond with a 404 instead.
To fix that, you will need to configure your production server to fallback to index.html for any requests that do not match a static file. The Vue Router docs provides configuration instructions for common server setups.
If you don't want to deal with this, or don't have a server enabling you to do this, you can switch history to hash mode in your router. Your routes will be accessible at /index.html#/dashboard and so on.
If you are running into this issue (as I was) in 2022 with a serverless vue 3 application and vuex, you can configure the hash-histroy like so
import { createRouter, createWebHashHistory } from 'vue-router'
import { type RouteRecordRaw } from 'vue-router'
import { Admin, Welcome } from '/#/views'
const routes: RouteRecordRaw[] = [
{
path: '/',
name: 'Welcome',
component: Welcome
},
{
path: '/admin',
name: 'Admin',
component: Admin
}
]
const router = createRouter({
history: createWebHashHistory(), // <--- this is important
routes
})
export { router }
See also: docs
router/index.js :
import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
}
]
const router = createRouter({
history: createWebHashHistory(process.env.BASE_URL),
routes
})
export default router
main_folder/vue.config.js
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false,
publicPath: ''
})
Important: use publicPath: '' and createWebHashHistory
That is all. You can now build. But remember that your links will appear as /index.html#/dashboard.

Vuejs lazy loading routes in webpack template

I have created vuejs project with vue-cli tools and webpack template.
vue init webpack my-project
I don't know how to implement lazy loading on routes with templates
currently i have two routes in router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '#/components/HelloWorld'
import Test from '#/components/Test'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/test',
name: 'test',
component: Test
}
]
})
And its imported in main.js
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
But it doesn't contain the lazy loading implementation how can i do it??
instead of using
import Test from '#/components/Test'
use as
const Test = () => import('#/components/Test');
lazy loading Documentataion
Nice way to do this:
function load (component) {
return () => import(`#/${component}.vue`)
}
...
routes: [
{ path: '/', component: load('Hello') },

vue-router cannot implement the two level routing

I'm trying to implement the two level routing by using vue-router
main.js
import Vue from 'vue'
import Router from 'vue-router'
import Hello from '../components/Hello.vue'
import First from '../page/firstPage.vue'
import Login from '../page/logIn.vue'
import Second from '../page/secondPage.vue'
Vue.use(Router)
const routes =[
{
path: '/',
component: Login
},
{
path: '/first',
component: First,
children: [ {
path: 'hello',
component: Hello
}
]
},
]
const router = new Router({
mode:'history',
routes:routes
})
export default router
But when I input http://localhost:8080/first/hello, it returns the 'First' component not the 'Hello' component.
thanks a lot

Categories

Resources