i have an issue loading a component in vue which should only be there if the route contains a specific string.
In this file there are multiple components as well, which need to be always loaded, only one needs to be loaded when needed.
So far i have this, but doesn't work:
import Vue from 'vue';
import { mapState } from 'vuex';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const routes = [
{
path: '/PATH',
name: 'Component3',
component: () =>
import(/* webpackChunkName: "vsf-layout-component3" */ './Component3'),
},
];
const router = new VueRouter({
routes,
});
export default {
router,
components: {
Component1: () => import(/* webpackChunkName: "vsf-layout-component1" */ './Component1'),
Component2: () => import(/* webpackChunkName: "vsf-layout-component2" */ './Component2'),
},
data: () {},
computed: () {},
};
maybe soneone has an idea?
Thanks in regards!
Related
Dynamic imports is needed for me, eg. i have 10 layouts, but user only visited 3 layouts, I should not import all of the layouts, since its consumed unnecessary resources.
Since its dynamic import, each time i switch between Login & Register path <RouterLink :to"{name: 'Login'}" /> & <RouterLink :to"{name: 'Register'}" />, I got rerender or dynamic import the layout again.
My question is what is the better way to handle it, without rerender or dynamic import the layout again? Or can I save the dynamic import component into the current vue 3 context?
App.vue this is my app with watching the router and switch the layout based on route.meta.layout
<template>
<component :is="layout.component" />
</template>
<script>
import DefaultLayout from "./layout/default.vue";
import {
ref,
shallowRef,
reactive,
shallowReactive,
watch,
defineAsyncComponent,
} from "vue";
import { useRoute } from "vue-router";
export default {
name: "App",
setup(props, context) {
const layout = shallowRef(DefaultLayout);
const route = useRoute();
watch(
() => route.meta,
async (meta) => {
if (meta.layout) {
layout = defineAsyncComponent(() =>
import(`./layout/${meta.layout}.vue`)
);
} else {
layout = DefaultLayout;
}
},
{ immediate: true }
);
return { layout };
},
};
</script>
router/index.js this is my router with layout meta
import { createRouter, createWebHistory } from "vue-router";
import Home from "#/views/Home.vue";
import NotFound from "#/views/NotFound.vue";
const routes = [
{
path: "/",
name: "Home",
component: Home,
},
{
path: "/login",
name: "Login",
meta: {
layout: "empty",
},
component: function () {
return import(/* webpackChunkName: "login" */ "../views/Login.vue");
},
},
{
path: "/register",
name: "Register",
meta: {
layout: "empty",
},
component: function () {
return import(/* webpackChunkName: "register" */ "../views/Register.vue");
},
},
{ path: "/:pathMatch(.*)", component: NotFound },
];
const router = createRouter({
history: createWebHistory(import.meta.env.VITE_GITLAB_BASE_PATH),
routes,
scrollBehavior(to, from, savedPosition) {
// always scroll to top
return { top: 0 };
},
});
export default router;
You could use AsyncComponent inside the components option and just use a computed property that returns the current layout, this will load only the current layout without the other ones :
components: {
layout1: defineAsyncComponent(() => import('./components/Layout1.vue')),
layout2: defineAsyncComponent(() => import('./components/Layout2.vue')),
},
Had this issue and Thorsten Lünborg of the Vue core team helped me out.
add the v-if condition and that should resolve it.
<component v-if="layout.name === $route.meta.layout" :is="layout">
I would like to check in my Vuex store whether a user has the 'admin' role before entering the /dashboard route. But I can't properly access data from store.getters.
I use Quasar (Vue.js) and Vuex + Typescript.
In the routes.ts file, on the beforeEnter() function, I can access getters from the store with a console.log(store.myStore.getters). Here I see userInfos inside:
I don't understand why I only get {} and not {...} (Note that if I click on it, I see its contents).
But if I call console.log(store.myStore.getters.userInfos), I don't see the data:
Here is index.ts (router):
import { route } from 'quasar/wrappers'
import VueRouter from 'vue-router'
import { Store } from 'vuex'
import { StateInterface } from '../store'
import routes from './routes'
export default route<Store<StateInterface>>(function ({ Vue }) {
Vue.use(VueRouter)
const Router = new VueRouter({
scrollBehavior: () => ({ x: 0, y: 0 }),
routes,
mode: process.env.VUE_ROUTER_MODE,
base: process.env.VUE_ROUTER_BASE
})
return Router
})
Here is routes.ts (router):
import { RouteConfig } from 'vue-router'
const routes: RouteConfig[] = [
{
path: '/',
component: () => import('layouts/Login.vue'),
children: [
{ path: '', component: () => import('pages/Index.vue') },
{ path: '/inscription', component: () => import('pages/SignUp.vue') },
{ path: '/connexion', component: () => import('pages/SignInPage.vue') }
]
},
{
path: '/main',
component: () => import('layouts/MainLayout.vue'),
children: [
{ path: '', component: () => import('pages/Index.vue') },
{ path: '/dashboard', component: () => import('pages/DashboardB2B.vue'),
beforeEnter: (to, from, next) => {
const store = require('../store')
console.log("before enter")
console.log(store.myStore.getters)
return next();
}, },
{
path: '/ajouter-un-referentiel',
component: () => import('pages/ReferentielMetier.vue')
},
{
path: '/init',
component: () => import('components/bot/BotSkeleton.vue')
}
]
},
{
path: '/bot',
component: () => import('layouts/Bot.vue'),
children: [
{
path: '/ajouter-un-referentiel',
component: () => import('pages/ReferentielMetier.vue')
},
{
path: '/init',
component: () => import('components/bot/BotSkeleton.vue')
}
]
},
// Always leave this as last one,
// but you can also remove it
{
path: '*',
component: () => import('pages/Error404.vue')
}
]
export default routes
And here is index.ts with the store (Vuex):
import Vue from 'vue'
import { store } from 'quasar/wrappers'
import Vuex from 'vuex'
Vue.use(Vuex)
import matching from './modules/matching'
import orga from './modules/organigrame'
import user from './modules/user'
export interface StateInterface {
example: unknown
}
let myStore: any
export default store(function({ Vue }) {
Vue.use(Vuex)
const Store = new Vuex.Store<StateInterface>({
modules: {
matching,
orga,
user
},
// enable strict mode (adds overhead!)
// for dev mode only
strict: !!process.env.DEBUGGING
})
myStore = Store
return Store
})
export {myStore}
EDIT: Looks like my console.log runs before the getters are loaded, because when I check out Vue developer tools, I see everything. How can I check the store if the store itself doesn't load before the beforeEnter function?
please try like this
store.myStore.getters["userInfos"]
I'm having exact issue, even if i use async/await :S
try this
router.beforeEach(async(to, from, next) => {
const userInfo = await store.getters.userInfos;
console.log(userInfo);
});
I use vue.js and I try to set a parameter id in axios.get request and I can't understand how exactly to do it
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Movie from './views/Movie.vue'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
// 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(/* webpackChunkName: "about" */ './views/About.vue')
},
{
path: '/movie/:m_id',
name: 'movie',
component: Movie
}
]
})
import Navbar from '../components/Navbar'
import axios from "axios"
export default {
components:{
Navbar
},
data () {
return {
movi: null,
}
},
mounted () {
axios
.get(`https://api.themoviedb.org/3/movie/${m_id}?api_key=7bc75e1ed95b84e912176b719cdeeff9&language=en-US`)
.then(response => (this.movi= response.data))
}
}
I am trying to pass to axios this id of the page to get information about that specific movie and I got stuck.
Any help?
You can try this to use your params from the URL:
// Retrieve the `m_id` param from the `this.$route.params` object:
this.$route.params.m_id
For more info see https://router.vuejs.org/api/#route-object-properties
#How can I do the same thing but in Vuex
import Vue from 'vue'
import Vuex from 'vuex'
import Axios from 'axios';
import router from './router'
Vue.use(Vuex)
Vue.use(Axios)
Vue.use(router)
export default new Vuex.Store({
// data() {
// return {
// m_id:this.$route.params.m_id
// }
// },
// m_id : this.$route.params.m_id,
state: {
video_key: [],
},
mutations: {
updateInfo (state , video_key){
state.video_key = video_key
}
},
getters:{
m_id : this.route.params.m_id
},
actions: {
fetchData({commit,getters}){
axios.get(`https://api.themoviedb.org/3/movie/${this.m_id}/videos?api_key=7bc75e1ed95b84e912176b719cdeeff9&language=en-US`)
.then(response =>{
commit('updateInfo',response.data.results[0].key)
})
}
}
})
I'm a bit new to using vue and webpack, and I'm trying to set up a form component. I'm getting an error saying "Uncaught (in promise) TypeError: Vue.use is not a function". The code that I am using is a modification of the code here: https://auralinna.blog/post/2018/how-to-build-a-complete-form-with-vue-js
I am loading Vue into my app asynchronously, so I think the issue may be that Vue isn't loaded yet, but I don't know enough to say for sure.
Here's my main app.js file:
// App main
const main = async () => {
// Import our CSS
//const Styles = await import(/* webpackChunkName: "styles" */ '../css/app.pcss');
// Async load the vue module
const Vue = await import(/* webpackChunkName: "vue" */ 'vue');
const VueI18n = await import(/* webpackChunkName: "vue-i18n" */ 'vue-i18n');
const Vuelidate = await import(/* webpackChunkName: "vuelidate" */ 'vuelidate');
const translations = await import(/* webpackChunkName: "translations" */ '../resources/translations');
const Scrollmagic = await import(/* webpackChunkName: "scrollmagic" */ 'scrollmagic');
Vue.use(VueI18n);
Vue.use(Vuelidate);
const i18n = new VueI18n({
locale: 'en',
fallbackLocale: 'en',
messages: translations
})
// process layout images
// Create our vue instance
const vm = new Vue.default({
el: "#app",
i18n,
delimiters: ['[[', ']]'],
components: {
'carousel': () => import(/* webpackChunkName: "vue-owl-carousel-br" */ '../vue/vue-owl-carousel-br/src/Carousel.vue'),
'appForm': () => import(/* webpackChunkName: "app-form" */ '../vue/form/form.vue'),
},
data: {
menuActive: false,
footerActive: false,
},
methods: {
},
mounted() {
},
});
};
The error message in the console says "Uncaught (in promise) TypeError: Vue.use is not a function" and it is happening at line 14: Vue.use(VueI18n);
I'm trying to resolve the error so that hopefully the form component will render. Can anyone point me to what I need to adjust to resolve this problem?
probably a stupid question especially as I am not sure if I am using VueJS or VueJS 2.0 but I am trying to get simple routing working where I can pick up the parameters / the path of the URL.
For example http://127.0.0.1/search/*****
Here is my main.js
import Vue from 'vue'
import App from './components/App'
import VueRouter from 'vue-router'
const routes = [
{ path: '/', name: 'Home', component: App },
{ path: 'search/:id', name: 'Search', component: App }
];
const router = new VueRouter({ mode: 'history', routes: routes });
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
render: h => h(App)
})
And on my App.component I am trying to get the :id
created: function() {
//this.filterTutorials();
this.searchTerm = this.$route.query.id;
if (this.searchTerm == null) {
this.searchTerm = this.$route.params.id;
}
console.log(this.searchTerm)
}
UPDATE
App and search were the same component but I have not split them out (same directory)
New main.js. It is not even calling the search page
import Vue from 'vue'
import App from './components/App'
import VueRouter from 'vue-router'
const routes = [
{ path: '/', name: 'Home', component: App },
{ path: '/search/:id', name: 'Search', component: () => import(/* webpackChunkName: "search" */ './components/Search.vue'), props: true }
];
const router = new VueRouter({ mode: 'history', routes: routes });
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
render: h => h(App)
})
I have also updated webpacks
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
vue: 'vue/dist/vue.js'
}
},
In your case, App is statically created before the route even resolves, so the created lifecycle hook would check for route parameter before it even existed (i.e., it would be undefined). I noticed both /search and / point to App, but you probably meant a component name like Search.
You can either dynamically import Search:
const routes = [
{
path: '/search/:id',
name: 'Search',
component: () => import(/* webpackChunkName: "search" */ './views/Search.vue')
}
]
Or you could use VueRouter's props: true to automatically set Search's id prop on navigation, obviating the check for the route parameters from created().
const routes = [
{
path: '/search/:id',
name: 'Search',
component: () => import(/* webpackChunkName: "search" */ './views/Search.vue'),
props: true,
}
]
demo