Vue2-Google-Maps Accessing gmapApi using beforeEnter() Route Guard - vue.js

Context: I am trying to get place data via the place_id on the beforeEnter() route guard. Essentially, I want the data to load when someone enters the url exactly www.example.com/place/{place_id}. Currently, everything works directly when I use my autocomplete input and then enter the route but it does not work when I directly access the url from a fresh tab. I believe the issue is because google has not been created yet.
Question: How can I access PlacesService() using the beforeEnter() route guard ?
Error: Uncaught (in promise) ReferenceError: google is not defined
Example Code:
In one of my store modules:
const module = {
state: {
selectedPlace: {}
},
actions: {
fetchPlace ({ commit }, params) {
return new Promise((resolve) => {
let request = {
placeId: params,
fields: ['name', 'rating', 'formatted_phone_number', 'geometry', 'place_id', 'website', 'review', 'user_ratings_total', 'photo', 'vicinity', 'price_level']
}
let service = new google.maps.places.PlacesService(document.createElement('div'))
service.getDetails(request, function (place, status) {
if (status === 'OK') {
commit('SET_SELECTION', place)
resolve()
}
})
})
},
},
mutations: {
SET_SELECTION: (state, selection) => {
state.selectedPlace = selection
}
}
}
export default module
In my store.js:
import Vue from 'vue'
import Vuex from 'vuex'
import placeModule from './modules/place-module'
import * as VueGoogleMaps from 'vue2-google-maps'
Vue.use(Vuex)
// gmaps
Vue.use(VueGoogleMaps, {
load: {
key: process.env.VUE_APP_GMAP_KEY,
libraries: 'geometry,drawing,places'
}
})
export default new Vuex.Store({
modules: {
placeModule: placeModule
}
})
in my router:
import store from '../state/store'
export default [
{
path: '/',
name: 'Home',
components: {
default: () => import('#/components/Home/HomeDefault.vue')
}
},
{
path: '/place/:id',
name: 'PlaceProfile',
components: {
default: () => import('#/components/PlaceProfile/PlaceProfileDefault.vue')
},
beforeEnter (to, from, next) {
store.dispatch('fetchPlace', to.params.id).then(() => {
if (store.state.placeModule.selectedPlace === undefined) {
next({ name: 'NotFound' })
} else {
next()
}
})
}
}
]
What I've tried:
- Changing new google.maps.places.PlacesService to new window.new google.maps.places.PlacesService
- Using beforeRouteEnter() rather than beforeEnter() as the navigation guard
- Changing google.maps... to gmapApi.google.maps... and gmapApi.maps...
- Screaming into the abyss
- Questioning every decision I've ever made
EDIT: I've also tried the this.$gmapApiPromiseLazy() proposed in the wiki here

The plugin adds a mixin providing this.$gmapApiPromiseLazy to Vue instances (components) only but you're in luck... it also adds the same method to Vue statically
Source code
Vue.mixin({
created () {
this.$gmapApiPromiseLazy = gmapApiPromiseLazy
}
})
Vue.$gmapApiPromiseLazy = gmapApiPromiseLazy
So all you need to do in your store or router is use
import Vue from 'vue'
// snip...
Vue.$gmapApiPromiseLazy().then(() => {
let service = new google.maps.places....
})

Related

Trouble getting user data inside vue-router from composition

I'm very new to vue.js, I am currently working on my final assignment for university.
I'm trying to get information of my user into my router, this works fine on my usual pages/components, but the techniques used on those files don't seem to work here. I've tried reading through some of the documention for router and composition, but I can't seem to figure out where I'm going wrong. This is my latest attempt as earlier I was not using setup() and getting the error; inject() can only be used inside setup() or functional components.
The problem is occuring with "useAuth," I'm not getting any data, my console.log(isAdmin) is displaying 'undefined,' this should be a boolean true/false.
Router code:
import { createWebHistory, createRouter } from "vue-router";
import Dashboard from "../pages/DashboardSDT.vue";
import Events from "../pages/EventsSDT.vue";
import Results from "../pages/ResultsSDT.vue";
import Admin from "../pages/AdminSDT.vue";
import Settings from "../pages/SettingsSDT.vue";
import Login from "../pages/LoginSDT.vue";
import Register from "../pages/RegisterSDT.vue";
import { getAuth } from "firebase/auth";
import useAuth from "../composition/useAuth";
const routes = [
{
path: "/",
name: "Dashboard",
component: Dashboard
},
{
path: "/Events",
name: "Events",
component: Events
},
{
path: "/Results",
name: "Results",
component: Results
},
{
path: "/Admin",
name: "Admin",
component: Admin,
meta: { onlyAdminUser: true }
},
{
path: "/Settings",
name: "Settings",
component: Settings,
meta: { onlyAuthUser: true }
},
{
path: "/Login",
name: "Login",
component: Login,
meta: { onlyGuestUser: true }
},
{
path: "/Register",
name: "Register",
component: Register,
meta: { onlyGuestUser: true }
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
router.beforeEach((to, _, next) => {
const isAuth = !!getAuth().currentUser;
const isAdmin = useAuth.admin;
console.log(isAdmin)
if (to.meta.onlyAuthUser) {
if (isAuth) {
next()
} else {
next({ name: "Login" })
}
// } else if(to.meta.onlyAdminUser) {
// if(isAdmin) {
// next()
// }
// else {
// next({name: "BasicUser"})
// }
} else if (to.meta.onlyGuestUser) {
if (isAuth) {
next({ name: "Dashboard" })
} else {
next()
}
} else {
next()
}
})
export default {
setup() {
return {
...useAuth()
}
},
...router
}
useAuth code:
import { useStore } from 'vuex'
import { computed } from 'vue'
export default function useAuth() {
const store = useStore();
const { state } = store;
const error = computed(() => state.user.auth.error);
const isProcessing = computed(() => state.user.auth.isProcessing);
const isAuthenticated = computed(() => store.getters["user/isAuthenticated"]);
const user = computed(() => state.user.data);
const admin = computed(() => state.user.data.admin);
return {
error,
isProcessing,
isAuthenticated,
user,
admin
}
}
vue-router's index file is not like a vue component file and does not have a setup() function. I've never tried but it's unlikely you can use composable functions either, especially when using vue composition API functions like computed()
You can however import the vuex store and access all it's state, getters, etc. like you want.
import store from '/store/index.js'; // or wherever your store lives
Then inside your router guard
const isAuthenticated = store.getters["user/isAuthenticated"];
const isProcessing = store.state.user.auth.isProcessing
// ...etc

Vue js conditional statement inside axios fetch API

I have a vue-router like this
import Vue from 'vue';
import Router from 'vue-router';
import http from './helpers/http';
import Home from './views/Home/Home.vue';
import HomeMentor from './views/Home/HomeMentor.vue';
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: '',
component: () => import(/* webpackChunkName: "Container" */ './components/Container.vue'),
children: [
{
path: '/',
name: 'Dashboard',
component: {
render(c) {
http.request('GET', '/profile').then( async ({ data }) => {
console.log(data.profile.email)
if (data.profile.email === "vickysultan08#gmail.com") {
console.log('sip')
return c(HomeMentor);
} else {
return c(Home);
}
});
}
},
}
],
beforeEnter: isAuthentication,
}
});
The thing is, only the return component inside the conditional statement that cannot executed inside axios statement as the result below
While the return component inside the conditonal statement can be executed outside the axios statement like this
children: [
{
path: '/',
name: 'Dashboard',
component: {
render(c) {
a = 10
if (a === 10) {
console.log('sip')
return c(HomeMentor);
} else {
return c(Home);
}
}
},
}
],
I'm quite new in Vue JS and have to continue other person's code. Any advice?
Unfortunately, render functions must be synchronous.
What you may be able to do instead is simply use an async function to return the component, ala Async Components and Lazy Loading Routes.
const Dashboard = () => http.request('GET', '/profile').then(({ data }) => {
console.log('profile email', data.profile.email)
let isMentor = data.profile.email === 'vickysultan08#gmail.com'
let componentPath = `./views/Home/${isMentor ? 'HomeMentor' : 'Home'}.vue`
return import(componentPath) // chains in the "import" promise
})
and then in your route...
component: Dashboard,
If lazy-loading the component isn't working for you, you could always try pre-loading it
import http from './helpers/http';
import Home from './views/Home/Home.vue';
import HomeMentor from './views/Home/HomeMentor.vue';
const Dashboard = () => http.request('GET', '/profile').then(({ data }) => {
let isMentor = data.profile.email === 'vickysultan08#gmail.com'
return isMentor ? HomeMentor : Home
})

What is the best approach in dynamic Vuex module initialisation when using Nuxt.js?

Lately, I have been building a large scale application that uses a lot of separate Vuex modules. Let's take a look at one of them (e.g. support-chat). Support chat is located on it's own separate page, and it would be redundant to pollute the store with this module on initial application load. My goal is to register this module dynamically when it's page is loaded. So my question is – where, when and how should I register that module?
I end up registering this module in the beforeCreate hook of the page component:
import supportChatModule from '#/vuex/modules/support-chat'
// ...
beforeCreate() {
this.$store.registerModule('support-chat', supportChatModule, { preserveState: process.client })
},
beforeDestroy() {
this.$store.unregisterModule('support-chat')
}
// ...
What pitfalls does that approach have?
It would be great if you can share your approach in solving that issue.
I struggled with this problem for a long time. I finally came up with a unique way.
I did this by moving register and unregister the modules for each page into the router file (router/index.js in my project) in beforeEach method and adding the required modules for each path.
Some modules are shared between pages, which solves this problem.
Some modules receive large amounts of data from the server, which is better than staying on the client side to avoid receiving this data again. I did this with a freezer.
This method can be improved.
router/index.js
router.beforeEach((to, from, next) => {
// unregister modules
if (from.meta.modules) {
for (const key in from.meta.modules.primary) {
if (to.meta.modules && to.meta.modules.primary.hasOwnProperty(key)) {
continue;
}
if (store.state.hasOwnProperty(key)) {
// don't unregister freeze modules
if (from.meta.modules.hasOwnProperty('freeze') && from.meta.modules.freeze.find(item => item == key)) {
continue;
}
store.unregisterModule(key);
}
}
}
// register modules
if (to.meta.modules) {
for (const key in to.meta.modules.primary) {
const module = to.meta.modules.primary[key]();
if (!store.state.hasOwnProperty(key)) {
store.registerModule(key, module.default);
}
}
}
});
And my paths are like this:
{
path: 'users',
name: 'users',
meta: {
modules: {
primary: {
user: () => require('#/store/modules/moduleUser')
}
},
},
component: () => import('../views/users.vue')
},
{
path: 'foods',
name: 'foods',
meta: {
modules: {
primary: {
food: () => require('#/store/modules/moduleFood'),
user: () => require('#/store/modules/moduleUser')
},
freeze: ['food']
},
},
component: () => import('../views/foods.vue')
},
Step 1:
Create a mixin, I named it register-vuex-module.js:
export const registerVuexModule = (name, module) => ({
beforeCreate() {
const { $store } = this
if ($store.hasModule(name)) $store.commit(`${name}/resetState`)
else $store.registerModule(name, module().default)
}
})
Step 2:
Use the mixin to import a module:
<template>
...
</template>
<script>
// Mixins
import { registerVuexModule } from '#/mixins/register-vuex-module'
export default {
mixins: [registerVuexModule('module-name', () => require('./vuex/MyVuexModule.js'))],
}
</script>
Step 3:
Make sure your Vuex module has a resetState mutation and also the state gets returned from a function. Here is an example of how MyVuexModule.js should look like:
const initialState = () => ({
count: null
})
export default {
namespaced: true,
state: initialState(),
mutations: {
// ...
resetState: state => Object.assign(state, initialState())
}
}

Vue-router: Using component method within the router

My first Vue project and I want to run a loading effect on every router call.
I made a Loading component:
<template>
<b-loading :is-full-page="isFullPage" :active.sync="isLoading" :can-cancel="true"></b-loading>
</template>
<script>
export default {
data() {
return {
isLoading: false,
isFullPage: true
}
},
methods: {
openLoading() {
this.isLoading = true
setTimeout(() => {
this.isLoading = false
}, 10 * 1000)
}
}
}
</script>
And I wanted to place inside the router like this:
router.beforeEach((to, from, next) => {
if (to.name) {
Loading.openLoading()
}
next()
}
But I got this error:
TypeError: "_components_includes_Loading__WEBPACK_IMPORTED_MODULE_9__.default.openLoading is not a function"
What should I do?
Vuex is a good point. But for simplicity you can watch $route in your component, and show your loader when the $route changed, like this:
...
watch: {
'$route'() {
this.openLoading()
},
},
...
I think it's fast and short solution.
I don't think you can access a component method inside a navigation guard (beforeEach) i would suggest using Vuex which is a vue plugin for data management and then making isLoading a global variable so before each route navigation you would do the same ... here is how you can do it :
Of course you need to install Vuex first with npm i vuex ... after that :
on your main file where you are initializing your Vue instance :
import Vue from 'vue'
import Vuex from 'vue'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
isLoading: false,
},
mutations: {
openLoading(state) {
state.isLoading = true
setTimeout(() => {
state.isLoading = false
}, 10000)
},
},
})
// if your router is on a separated file just export the store and import it there
const router = new VueRouter({
routes: [
{
// ...
},
],
})
router.beforeEach((to, from, next) => {
if (to.name) {
store.commit('openLoading')
}
next()
})
new Vue({
/// ....
router,
store,
})
In your component:
<b-loading :is-full-page="isFullPage" :active.sync="$store.state.isLoading" :can-cancel="true"></b-loading>

Vue-router dynamic load menu tree

I'm trying to create a menu tree with vue-router by ajax request,but the $mount function was called before the ajax request responsed, so the router in the Vue instance always null.
Is there any good solution here?
Here is my code (index.js):
import Vue from 'vue';
import Element from 'element-ui';
import entry from './App.vue';
import VueRouter from 'vue-router';
import VueResource from 'vue-resource';
import Vuex from 'vuex'
import configRouter from './route.config';
import SideNav from './components/side-nav';
import Css from './assets/styles/common.css';
import bus from './event-bus';
import dynamicRouterConfig from './dynamic.router';
Vue.use(VueRouter);
Vue.use(Element);
Vue.use(VueResource);
Vue.use(Vuex);
Vue.http.interceptors.push((request, next) => {
bus.$emit('toggleLoading');
next(() => {
bus.$emit('toggleLoading');
})
})
Vue.component('side-nav', SideNav);
app = new Vue({
afterMounted(){
console.info(123);
},
render: h => h(entry),
router: configRouter
});
app.$mount('#app');
route.config.js:
import navConfig from './nav.config';
import dynamicRouterConfig from './dynamic.router';
let route = [{
path: '/',
redirect: '/quickstart',
component: require('./pages/component.vue'),
children: []
}];
const registerRoute = (config) => {
//require(`./docs/zh-cn${page.path}.md`)
//require(`./docs/home.md`)
function addRoute(page) {
if (page.show == false) {
return false;
}
let component = page.path === '/changelog' ? require('./pages/changelog.vue') : require(`./views/alert.vue`);
if (page.path === '/edit') {
component = require('./views/edit.vue');
}
let com = component.default || component;
let child = {
path: page.path.slice(1),
meta: {
title: page.title || page.name,
description: page.description
},
component: com
};
route[0].children.push(child);
}
//if (config && config.length>0) {
config.map(nav => {
if (nav.groups) {
nav.groups.map(group => {
group.list.map(page => {
addRoute(page);
});
});
} else if (nav.children) {
nav.children.map(page => {
addRoute(page);
});
} else {
addRoute(nav);
}
});
//}
return { route, navs: config };
};
const myroute = registerRoute(navConfig);
let guideRoute = {
path: '/guide',
name: 'Guide',
redirect: '/guide/design',
component: require('./pages/guide.vue'),
children: [{
path: 'design',
name: 'Design',
component: require('./pages/design.vue')
}, {
path: 'nav',
name: 'Navigation',
component: require('./pages/nav.vue')
}]
};
let resourceRoute = {
path: '/resource',
name: 'Resource',
component: require('./pages/resource.vue')
};
let indexRoute = {
path: '/',
name: 'Home',
component: require('./pages/index.vue')
};
let dynaRoute = registerRoute(dynamicRouterConfig).route;
myroute.route = myroute.route.concat([indexRoute, guideRoute, resourceRoute]);
myroute.route.push({
path: '*',
component: require('./docs/home.md')
});
export const navs = myroute.navs;
export default myroute.route;
And dynamic.router.js:
module.exports = [
{
"name": "Edit",
"path": "/edit"
}
]
Now the static route config is woking fine ,but how can I load data from server side by ajax request in the route.config.js instead of static data.
Waiting for some async request at page render is fine, just set empty initial values in the data section of component like:
data() {
someStr: '',
someList: []
}
and make sure you handle the empty values well without undefined errors trying to read things like someList[0].foo.
Then when the request comes back, set the initially empty values to those real data you get from the request.
Giving the user some visual indicate that you're fetching the data would be a good practice. I've found v-loading in element-ui useful for that.