Change language on direct url input (VueJs) - javascript

I have implemented localisation with vue-i18n.
my main.js
import Vue from 'vue'
import { i18n } from './plugins/i18n'
import Cookie from "vue-cookie";
if (!Cookie.get('locale')) {
Cookie.set('locale', 'en', 1)
}
new Vue({
el: '#app',
router,
i18n,
template: '<App/>',
components: {App},
render: h => h(App),
mounted() {},
data: {
event: false
}
}).$mount();
my i18n.js plugin
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import enTranslations from '../../lang/en'
import slTranslations from '../../lang/sl'
import Cookie from 'vue-cookie'
Vue.use(VueI18n);
export const i18n = new VueI18n({
locale: Cookie.get('locale'),
fallbackLocale: 'en', // fallback option
messages: { en: enTranslations, sl: slTranslations}
});
My routes
{
path: '/:lang',
component: {
template: '<router-view></router-view>'
},
children: [
{
path: '',
name: 'Home',
component: Home
},
{
path: 'contact',
name: 'Contact',
component: Contact
}
]
}
And my switch language function in my navigation component
setLocale(locale) {
let selectedLang = locale.toLowerCase();
Cookie.set('locale', selectedLang, 1);
this.$router.push({name: this.$route.name, params: {lang: selectedLang}});
location.reload();
},
So far everything ok and working when I switch language via upper function setLocale(). The problem appears when user inputs url directly for example:
I have currently selected english language and then user visits page directly via url, let's say: localhost:8080/sl/contact
If I understand documentation correctly I should configure this in routes with beforeEnter function. So my current implementation looks like this.
beforeEnter: (to, from, next) => {
let selectedLang = to.params.lang.toLowerCase();
Cookie.set('locale', selectedLang, 1);
next();
},
But this doesn't do the trick, because it's only working on second reload.
So the cooke locale is set to correct language, but looks like them component code happens before so UI is still in old language. When I refresh again, then content of page is in correct language. How can I overcome this problem?
If you need any additional information's please let me know and I will provide. Thank you!

When you navigate from localhost:8080/sl/contact to localhost:8080/en/contact, the same **'Contact'**vue component instance will be reused. Since both routes render the same component,
Please refer to the documentation:
https://router.vuejs.org/guide/essentials/dynamic-matching.html#reacting-to-params-changes.
To re-render the contact component you could either watch the $route object or use in-component navigation guards beforeRouteUpdate to react to changes and then reload your component or any application logic you wish to execute.
To know further about in-component navigation guards please refer to this link https://router.vuejs.org/guide/advanced/navigation-guards.html#per-route-guard
Please try this,
Option 1:
watch:{
$route(to, from){
let selectedLang = to.params.lang.toLowerCase();
Cookie.set('locale', selectedLang, 1);
//reload your component
}
Option 2:
beforeRouteUpdate: (to, from, next) => {
let selectedLang = to.params.lang.toLowerCase();
Cookie.set('locale', selectedLang, 1);
next();
},

Related

Vue router - how to have multiple components loaded on the same route path based on user role?

I have app where user can login in different roles, eg. seller, buyer and admin.
For each user I'd like to show dashboard page on the same path, eg. http://localhost:8080/dashboard
However, each user will have different dashboard defined in different vue components, eg. SellerDashboard, BuyerDashboard and AdminDashboard.
So basically, when user opens http://localhost:8080/dashboard vue app should load different component based on the user role (which I store in vuex). Similarly, I'd like to have this for other routes. For example, when user goes to profile page http://localhost:8080/profile app should show different profile component depending on the logged in user.
So I'd like to have the same route for all users roles as opposed to have different route for each user role, eg. I don't want user role to be contained in url like following: http://localhost:8080/admin/profile and http://localhost:8080/seller/profile etc...
How can I implement this scenario with vue router?
I tried using combination of children routes and per-route guard beforeEnter to resolve to a route based on user role. Here is a code sample of that:
in router.js:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import store from '#/store'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'home',
component: Home,
beforeEnter: (to, from, next) => {
next({ name: store.state.userRole })
},
children: [
{
path: '',
name: 'admin',
component: () => import('#/components/Admin/AdminDashboard')
},
{
path: '',
name: 'seller',
component: () => import('#/components/Seller/SellerDashboard')
},
{
path: '',
name: 'buyer',
component: () => import('#/components/Buyer/BuyerDashboard')
}
]
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
in store.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
userRole: 'seller' // can also be 'buyer' or 'admin'
}
})
App.vue contains parent router-view for top-level routes, eg. map / to Home component and /about to About component:
<template>
<router-view/>
</template>
<script>
export default {
name: 'App',
}
</script>
And Home.vue contains nested router-view for different user's role-based components:
<template>
<div class="home fill-height" style="background: #ddd;">
<h1>Home.vue</h1>
<!-- nested router-view where user specific component should be rendered -->
<router-view style="background: #eee" />
</div>
</template>
<script>
export default {
name: 'home'
}
</script>
But it doesn't work because I get Maximum call stack size exceeded exception in browser console when I call next({ name: store.state.userRole }) in beforeEnter. The exception is:
vue-router.esm.js?8c4f:2079 RangeError: Maximum call stack size exceeded
at VueRouter.match (vue-router.esm.js?8c4f:2689)
at HTML5History.transitionTo (vue-router.esm.js?8c4f:2033)
at HTML5History.push (vue-router.esm.js?8c4f:2365)
at eval (vue-router.esm.js?8c4f:2135)
at beforeEnter (index.js?a18c:41)
at iterator (vue-router.esm.js?8c4f:2120)
at step (vue-router.esm.js?8c4f:1846)
at runQueue (vue-router.esm.js?8c4f:1854)
at HTML5History.confirmTransition (vue-router.esm.js?8c4f:2147)
at HTML5History.transitionTo (vue-router.esm.js?8c4f:2034)
and thus nothing is rendered.
Is there a way I can solve this?
You might want to try something around this solution:
<template>
<component :is="compName">
</template>
data: () {
return {
role: 'seller' //insert role here - maybe on `created()` or wherever
}
},
components: {
seller: () => import('/components/seller'),
admin: () => import('/components/admin'),
buyer: () => import('/components/buyer'),
}
Or if you prefer maybe a bit more neat (same result) :
<template>
<component :is="loadComp">
</template>
data: () => ({compName: 'seller'}),
computed: {
loadComp () {
const compName = this.compName
return () => import(`/components/${compName}`)
}
}
This will give you the use of dynamic components without having to import all of the cmps up front, but using only the one needed every time.
Such code retrieves component code only for a given role:
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import store from "../store";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "home",
component: () => {
switch (store.state.userRole) {
case "admin":
return import("../components/AdminDashboard");
case "buyer":
return import("../components/BuyerDashboard");
case "seller":
return import("../components/SellerDashboard");
default:
return Home;
}
}
}
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes
});
export default router;
One approach would be to use a dynamic component. You could have a single child route whose component is also non-specific (e.g. DashboardComponent):
router.js
const routes = [
{
path: '/',
name: 'home',
children: [
{
path: '',
name: 'dashboard',
component: () => import('#/components/Dashboard')
}
]
}
]
components/Dashboard.vue
<template>
<!-- wherever your component goes in the layout -->
<component :is="dashboardComponent"></component>
</template>
<script>
import AdminDashboard from '#/components/Admin/AdminDashboard'
import SellerDashboard from '#/components/Seller/SellerDashboard'
import BuyerDashboard from '#/components/Buyer/BuyerDashboard'
const RoleDashboardMapping = {
admin: AdminDashboard,
seller: SellerDashboard,
buyer: BuyerDashboard
}
export default {
data () {
return {
dashboardComponent: RoleDashboardMapping[this.$store.state.userRole]
}
}
}
</script>
You run into the Maximum call stack size exceeded exception because the next({ name: store.state.userRole }) will trigger another redirection and call the beforeEnter again and thus results in infinite loop.
To solve this, you can check on the to param, and if it is already set, you can call next() to confirm the navigation, and it will not cause re-direction. See code below:
beforeEnter: (to, from, next) => {
// Helper to inspect the params.
console.log("to", to, "from", from)
// this is just an example, in your case, you may need
// to verify the value of `to.name` is not 'home' etc.
if (to.name) {
next();
} else {
next({ name: store.state.userRole })
}
},
I faced the same problem (I use Meteor JS with Vue JS) and I found the way to do it with the render function to load different components on the same route. So, in your case it should be:
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import AdminDashboard from "../components/AdminDashboard";
import BuyerDashboard from "../components/BuyerDashboard";
import SellerDashboard from "../components/SellerDashboard";
import store from "../store";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "home",
component: {
render: (h) => {
switch (store.state.userRole) {
case "admin":
return h(AdminDashboard);
case "buyer":
return h(BuyerDashboard);
case "seller":
return h(SellerDashboard);
default:
return h(Home);
}
}
}
}
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes
});
export default router;
Note that this solution also works but only for the first time, if you enter again to that route, the last component loaded it will keep (you will need to reload the page). So, with the render function it always load the new component.
Vue Router 4 (Vue 3)
If you are using Vue Router 4 (usable only with Vue 3), one alternative solution is to use dynamic routing
This new feature allows us to remove/add routes on the fly.
// router.js
import { createRouter, createWebHistory } from 'vue-router'
import store from "../store";
import Home from "../views/Home.vue";
import About from "../views/About.vue";
// all routes independent of user role
const staticRoutes = [
{
path: "/",
name: "home",
component: Home,
},
{
path: "/about",
name: "about",
component: About,
},
]
const getRoutesForRole = (role) => {
// imlementation can vary - see the rest of the answer
}
// routes used at app initialization
const initialRoutes = [...staticRoutes, ...getRoutesForRole(store.state.userRole)]
const router = createRouter({
history: createWebHistory(),
routes: initialRoutes,
})
export default router
export const updateRoutesForRole = () {
// implementation can vary - see the rest of the answer
}
How to generate dynamic routes - getRoutesForRole
The implementation of course depends on many factors - how many routes (and also roles) do you have is probably most important.
With just 2 or 3 routes (and not many roles) it is just fine to use a static definition:
const routesPerRole = {
"admin": [
{
path: "/dashboard",
name: "dashboard",
component: () => import("../components/AdminDashboard.vue")
}, // more routes follow....
],
"seller": [
{
path: "/dashboard",
name: "dashboard",
component: () => import("../components/SellerDashboard.vue")
}, // more routes follow....
],
"buyer": [
{
path: "/dashboard",
name: "dashboard",
component: () => import("../components/BuyerDashboard.vue")
}, // more routes follow....
],
}
const getRoutesForRole = (role) => {
if(!role) return []
return routesPerRole[role]
}
If you have many routes and/or many roles, you probably want something more generic. First we need some good naming convention - for example lets say that we will organize our components in a directory structure like this: #/components/${role}/${componentName}.vue
Then we can use Webpacks dynamic import
const routeTemplates = [
{
path: "/dashboard",
name: "dashboard",
component: 'Dashboard'
},
]
const getRoutesForRole = (role) => {
if(!role) return []
const routesForRole = routeTemplates.map(route => ({
...route,
component: () => import(`#/components/${role}/${route.component}.vue`)
}))
return routesForRole
}
Note that thanks to how import() with dynamic expression works in Webpack this will make Webpack to create new JS chunk for each component in #/components folder which may be not what you want.
Easy fix is to move the "role dependent" components into it's own subfolder so instead of using #/components/admin/.... just use #/components/perRoleComponents/admin/.... and
import(`#/components/perRoleComponents/${role}/${route.component}.vue`)
Other solution is to use different import() statement for each role. This will also allow us to use Webpacks "magic comments" and for example force Webpack to pack all components for each role into single js chunk:
const routeTemplates = [
{
path: "/dashboard",
name: "dashboard",
component: 'Dashboard'
},
]
const getComponentLoader = (role, componentName) => {
switch(role) {
"admin": return () => import(
/* webpackChunkName: "admin-components" */
/* webpackMode: "lazy-once" */
`#/components/admin/${componentName}.vue`)
"seller": return () => import(
/* webpackChunkName: "seller-components" */
/* webpackMode: "lazy-once" */
`#/components/seller/${componentName}.vue`)
"buyer": return () => import(
/* webpackChunkName: "buyer-components" */
/* webpackMode: "lazy-once" */
`#/components/buyer/${componentName}.vue`)
}
}
const getRoutesForRole = (role) => {
if(!role) return []
const routesForRole = routeTemplates.map(route => ({
...route,
component: getComponentLoader(role, route.component)
}))
return routesForRole
}
How to update routes - updateRoutesForRole()
Easiest scenario is when each role has same set of routes and just wants to use a different component. In this case to switch the routes when role changes we can just use addRoute
Add a new route record to the router. If the route has a name and there is already an existing one with the same one, it removes it first.
export const updateRoutesForRole = () {
const role = store.state.userRole
const routesForRole = getRoutesForRole(role)
routesForRole.forEach(r => router.addRoute(r))
}
For more complicated scenarios where not all routes are available for all roles, previous routes (for previous active role - if any) must be removed 1st using removeRoute function. Also our getRoutesForRole() must be different. One solution is to use route meta fields
const routeTemplates = [
{
path: "/dashboard",
name: "dashboard",
component: 'Dashboard',
meta: { forRoles: ['admin', 'seller'] }
},
]
const getRoutesForRole = (role) => {
if(!role) return []
const routesForRole = routeTemplates
.filter(route => route.meta?.forRoles?.includes(role))
.map(route => ({
...route,
component: () => import(`#/components/${role}/${route.component}.vue`)
}))
return routesForRole
}
export const updateRoutesForRole = () {
const role = store.state.userRole
// delete previous 1st
router.getRoutes()
.filter(route => route.meta?.forRoles)
.forEach(route => router.removeRoute(route.name))
const routesForRole = getRoutesForRole(role)
routesForRole.forEach(r => router.addRoute(r))
}
Router v3 (for Vue 2)
Note that Router v3 (and earlier) was never designed with dynamic routing in mind. There is no removeRoute() function. There is a addRoute() so some of the scenarios described above could be probably possible but it currently (Router v3.5.3) does not work as described in the documentation
One way to solve this is to create three separate components DashboardForAdmin, DashBoardForSeller, and DashBoardForBuyer for three types of users.
Then use a mixin.js
export default {
data: function () {
return {
userType : "buyer"; // replace this with a function that returns "seller", "buyer", or "admin"
}
}
}
Create a Vue component DashboardContainer renders the correct dashboard component based on mixin return value
<template>
<div>
<div v-if="userType === 'admin'">
<DashboardForAdmin />
</div>
<div v-else-if="userType === 'buyer'">
<DashboardForBuyer />
</div>
<div v-else>
<DashboardForSeller />
</div>
</div>
</template>
<script>
import mixin from '#/mixin.js';
import DashboardForAdmin from '#/components/DashboardForAdmin.vue';
import DashBoardForSeller from '#/components/DashBoardForSeller.vue';
import DashBoardForBuyer from '#/components/DashBoardForBuyer.vue';
export default {
mixins: [mixin],
components: {
DashboardForAdmin, DashBoardForSeller, DashBoardForBuyer
},
};
</script>
Now you can add a single route for the DashboardContainer

how to prevent or stop parent component to re-render in vuejs

Hi Guys i'm trying to create a look something like Bootstrap Nav Tabs but with Vuejs and Vue Router i also want to change the url in browser
here is my code for VueRouter
it is working fine but the Parent component(UserProfile) get re-render every time i switch between UserProfilePosts or UserDetails because i know my code going to be larger and this is not a good user experience,Thanks
{
path:'/:id',
component:UserProfile,
children: [
{ path: '', component: UserProfilePosts },
{ path: 'details', component: UserDetails },
],
meta:{
requiresAuth:true
}
}
Main Component(UserProfile):
<template>
<div class="container-fluid">
<h1>UserProfile</h1>
<router-link to="/username">Post's</router-link>
<router-link to="/username/details">Details</router-link>
<router-view></router-view>
</div>
<script>
export default{
created(){
console.log('created');
}
}</script>
You can try using Vuex with vex-persist. Vue refresh and reload the html each time it is asked. I am new to vue and this was how I implemented it, though it may not be the best solution.
VueX is the one central source of truth that your components can look for information. It will be easier passing down as prop and all the components just head to the 'store' for information
This stores the information as a local / session storage. For more information check out : https://github.com/championswimmer/vuex-persistuex-persist
import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersistence from 'vuex-persist'
const vuexLocal = new VuexPersistence({
storage: window.sessionStorage
})
Vue.use(Vuex)
export default new Vuex.Store({
plugins: [vuexLocal.plugin],
state: {
database: []
},
mutations: {
pushToDatabase: (state, val) => {
state.database.push (val}
}
},
getters: {
getData: state => {
return state.database
}
}
})

Conditional route in Vue.js

I have two different views that I'd like to show for the same path depending on whether a token is in LocalStorage or not. I could move the logic directly into the view itself, but I was curious to know whether there's a way to it in the Router.
Something like:
export default new Router({
mode: "history",
base: process.env.BASE_URL,
routes: [
{
path: "/",
name: "home",
component: function() {
if (...) {
return ViewA
} else {
return ViewB
}
}
},
]
});
I tried with the above code but didn't work. The app builds fine but none of the two views is shown.
A getter could be used for this, but, you will need to be sure to import both components:
import ViewA from '#/views/ViewA'
import ViewB from '#/views/ViewB'
export default new Router({
mode: "history",
base: process.env.BASE_URL,
routes: [
{
path: "/",
name: "home",
get component() {
if (...) {
return ViewA;
} else {
return ViewB;
}
}
},
]
});
In my notes, I have written "cannot find documentation on this" pertaining to the above. While not specifically related, however, it might be helpful to review using some information from https://stackoverflow.com/a/50137354/3261560 regarding the render function. I've altered what is discussed there using your example above.
component: {
render(c) {
if (...) {
return c(ViewA);
} else {
return c(ViewB);
}
}
}
I was answering the same question before and you can see it here.
Here is an example:
routes: [
{
path: '*',
beforeEnter(to, from, next) {
let components = {
default: [A, B, C][Math.floor(Math.random() * 100) % 3],
};
to.matched[0].components = components;
next();
}
},
... where A, B, C are components and they are randomly chosen every time the route changes. So in your case you can just alter beforeEnter logic to your needs and set any component you wish before routing to it.
Alright so I found a simple way to do this using the webpack lazy loading functionality in vue router with vuex store state property;
{
path: '/',
component: () => {
if (store.state.domain) {
return import(/* webpackChunkName: "app-home" */ '../views/AppHome.vue');
} else {
return import(/* webpackChunkName: "home" */ '../views/Home.vue');
}
}
},
With the above code, my home component is dynamically imported and used the route component depending on the value of domain property in my vuex store. Please note that you have to set up vuex store and import it in your router for this to work.
The solution in the question would have worked if you returned the component as an import.

Vue router not loading component

So ive been looking into vue and been experiencing an issue which i cant seem to find the solution for. Im using Vue and Vue-router. I started with the basic vue + webpack template which gave the initial boilerplate.
I've successfully added additional routes to the predefined routes which is working as expected (games, tournaments, stats and users routes works just fine). However now im unable to get additional routes to work. the "gaming" route doesnt work, ive also tried adding additional routes which does not seem to work either.
So this is my current router file (index.js):
import Vue from 'vue'
import Router from 'vue-router'
const Gaming = () => import('#/components/gaming.vue');
const Home = () => import('#/components/home.vue');
const Game = () => import('#/components/game.vue');
const Tournament = () => import('#/components/tournament.vue');
const Users = () => import('#/components/users.vue');
const Stats = () => import('#/components/stats.vue');
const router = new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/games',
name: 'Game',
component: Game,
},
{
path: '/wtf',
name: 'Gaming',
components: Gaming,
},
{
path: '/tournaments',
name: 'Tournament',
component: Tournament
},
{
path: '/users',
name: 'Users',
component: Users
},
{
path: '/stats',
name: 'Stats',
component: Stats
}
]
});
export default router;
Vue.use(Router);
All my routes works as expected except the "Gaming" route. The "Gaming" component looks like this:
<template>
<div>
<h1>WTF?!?!?!?!?=!?!</h1>
</div>
</template>
<script>
export default {
name: 'Gaming',
components: {},
data() {
return {}
},
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
</style>
Ive tried to pretty much copy/paste a working component, And only change the name, as well as the template. But it seems to have issues. Initially i had done the route component imports the normal "boilerplate" way
import Stats from '#/components/Stats'
Which pretty much had the same result, Except this would cause an exception when attempting to navigate to the "gaming" route.
Cannot read property '$createElement' of undefined
at render (eval at ./node_modules/vue-loader/lib/template-compiler/index.js?{"id":"data-v-c9036282","hasScoped":false,"transformToRequire":{"video":["src","poster"],"source":"src","img":"src","image":"xlink:href"},"buble":{"transforms":{}}}!./node_modules/vue-loader/lib/selector.js?type=template&index=0!./src/components/gaming.vue (app.js:4240), <anonymous>:3:16)
All other routes worked. Ive also tried to re-create all the files and re-do the specific route which doesnt seem to work either. So im at a loss of what i can do to fix this issue?
Here i attempt to inspect the route, And as you can see the component is missing "everything"
Inspecting the route
Also tried looking with the vue addon for chrome, Where the component does not get loaded into the view
Vue Chrome Extension
Uploaded the project to gdrive if someone want to tweak around with it
Google Drive Link
Found the issue:
const router = new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/games',
name: 'Game',
component: Game,
},
{
path: '/wtf',
name: 'Gaming',
components <----------: Gaming,
// Should be component not componentS
},
{
path: '/tournaments',
name: 'Tournament',
component: Tournament
},
...
Also, you should use the standard method of importing. Without that error, I would've never found the issue.

How to load all server side data on initial vue.js / vue-router load?

I'm currently making use of the WordPress REST API, and vue-router to transition between pages on a small single page site. However, when I make an AJAX call to the server using the REST API, the data loads, but only after the page has already rendered.
The vue-router documentation provides insight in regards to how to load data before and after navigating to each route, but I'd like to know how to load all route and page data on the initial page load, circumventing the need to load data each time a route is activated.
Note, I'm loading my data into the acf property, and then accessing it within a .vue file component using this.$parent.acfs.
main.js Router Code:
const router = new VueRouter({
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/tickets', component: Tickets },
{ path: '/sponsors', component: Sponsors },
],
hashbang: false
});
exports.router = router;
const app = new Vue({
router,
data: {
acfs: ''
},
created() {
$.ajax({
url: 'http://localhost/placeholder/wp-json/acf/v2/page/2',
type: 'GET',
success: function(response) {
console.log(response);
this.acfs = response.acf;
// this.backgroundImage = response.acf.background_image.url
}.bind(this)
})
}
}).$mount('#app')
Home.vue Component Code:
export default {
name: 'about',
data () {
return {
acf: this.$parent.acfs,
}
},
}
Any ideas?
My approach is to delay construction of the store and main Vue until my AJAX call has returned.
store.js
import Vue from 'vue';
import Vuex from 'vuex';
import actions from './actions';
import getters from './getters';
import mutations from './mutations';
Vue.use(Vuex);
function builder(data) {
return new Vuex.Store({
state: {
exams: data,
},
actions,
getters,
mutations,
});
}
export default builder;
main.js
import Vue from 'vue';
import VueResource from 'vue-resource';
import App from './App';
import router from './router';
import store from './store';
Vue.config.productionTip = false;
Vue.use(VueResource);
Vue.http.options.root = 'https://miguelmartinez.com/api/';
Vue.http.get('data')
.then(response => response.json())
.then((data) => {
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store: store(data),
template: '<App/>',
components: { App },
});
});
I have used this approach with other frameworks such as Angular and ExtJS.
You can use navigation guards.
On a specific component, it would look like this:
export default {
beforeRouteEnter (to, from, next) {
// my ajax call
}
};
You can also add a navigation guard to all components:
router.beforeEach((to, from, next) => {
// my ajax call
});
One thing to remember is that navigation guards are async, so you need to call the next() callback when the data loading is finished. A real example from my app (where the guard function resides in a separate file):
export default function(to, from, next) {
Promise.all([
IngredientTypes.init(),
Units.init(),
MashTypes.init()
]).then(() => {
next();
});
};
In your case, you'd need to call next() in the success callback, of course.
I've comprised my own version based on all the great responses to this post.. and several years having passed by as well giving me more tools.
In main.js, I use async/await to call a prefetch service to load any data that must be there on startup. I find this increases readability. After I get the data comms, I then dispatch it to the appropriate vuex store module in the beforeCreate() hook.
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import { prefetchAppData } from '#/services/prefetch.service';
(async () => {
let comms = await prefetchAppData();
new Vue({
router,
store,
beforeCreate() {
store.dispatch('communityModule/initialize', comms);
},
mounted() {},
render: h => h(App)
}).$mount('#app');
})();
I feel compelled to warn those be careful what you prefetch. Try to do this sparingly as it does delay initial app loading which is not ideal for a good user experience.
Here's my sample prefetch.service.js which does the data load. This of course could be more sophisticated.
import api from '#api/community.api';
export async function prefetchAppData() {
return await api.getCommunities();
}
A simple vue store. This store maintains a list of 'communities' that the app requires to be loaded before application start.
community.store.js (note im using vuex modules)
export const communityModule = {
namespaced: true,
state: {
communities: []
},
getters: {
communities(state) {
return state.communities;
},
},
mutations: {
SET_COMMUNITIES(state, communities) {
state.communities = communities;
}
},
actions: {
// instead of loading data here, it is passed in
initialize({ commit }, comms) {
commit('SET_COMMUNITIES', comms);
}
}
};
Alright, I finally figured this thing out. All I'm doing is calling a synchronous ajax request within my main.js file where my root vue instance is instantiated, and assigning a data property the requested data as so:
main.js
let acfData;
$.ajax({
async: false,
url: 'http://localhost/placeholder/wp-json/acf/v2/page/2',
type: 'GET',
success: function(response) {
console.log(response.acf);
acfData = response.acf;
}.bind(this)
})
const router = new VueRouter({
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About },
{ path: '/tickets', component: Tickets },
{ path: '/sponsors', component: Sponsors },
],
hashbang: false
});
exports.router = router;
const app = new Vue({
router,
data: {
acfs: acfData
},
created() {
}
}).$mount('#app')
From here, I can use the pulled data within each individual .vue file / component like so:
export default {
name: 'app',
data () {
return {
acf: this.$parent.acfs,
}
},
Finally, I render the data within the same .vue template with the following:
<template>
<transition
name="home"
v-on:enter="enter"
v-on:leave="leave"
v-bind:css="false"
mode="out-in"
>
<div class="full-height-container background-image home" v-bind:style="{backgroundImage: 'url(' + this.acf.home_background_image.url + ')'}">
<div class="content-container">
<h1 class="white bold home-title">{{ acf.home_title }}</h1>
<h2 class="white home-subtitle">{{ acf.home_subtitle }}</h2>
<div class="button-block">
<button class="white home-button-1">{{ acf.link_title_1 }}</button>
<button class="white home-button-2">{{ acf.link_title_2 }}</button>
</div>
</div>
</div>
</transition>
</template>
The most important piece of information to take away, is that all of the ACF data is only being called ONCE at the very beginning, compared to every time a route is visited using something like beforeRouteEnter (to, from, next). As a result, I'm able to get silky smooth page transitions as desired.
Hope this helps whoever comes across the same problem.
Check this section in docs of Vue Router
https://router.vuejs.org/guide/advanced/data-fetching.html
So first of you have to write method that would fetch data from your endpoint, and then use watcher to watch route.
export default {
watch: {
'$route': 'fetchItems'
},
methods: {
fetchItems() {
// fetch logic
}
}
}
Since you are working with WP Rest API, feel free to check my repo on Github https://github.com/bedakb/vuewp/blob/master/public/app/themes/vuewp/app/views/PostView.vue#L39

Categories