Vue Router - call function after route has loaded - javascript

I'm working on a project where I need to call a function AFTER the route has finished loading. However, when using the 'watch' functionality, it only loads on route change, but does so before route has finished loading. So when I attempt to run a script that targets DOM elements on the page, those elements don't exist yet. Is there any functionality in Vue Router that would allow me to wait until everything is rendered before running the script?
const app = new Vue({
el: '#app',
router,
watch: {
'$route': function (from, to) {
function SOMEFUNCTION()
}
},
data: {
some data
},
template: `
<router-view/>
`
})

You should use Vue.nextTick
In your case this would translate to:
const app = new Vue({
el: '#app',
router,
watch: {
$route() {
this.$nextTick(this.routeLoaded);
}
},
data() {
return {};
},
methods: {
routeLoaded() {
//Dom for the current route is loaded
}
},
mounted() {
/* The route will not be ready in the mounted hook if it's component is async
so we use $router.onReady to make sure it is.
it will fire right away if the router was already loaded, so catches all the cases.
Just understand that the watcher will also trigger in the case of an async component on mount
because the $route will change and the function will be called twice in this case,
it can easily be worked around with a local variable if necessary
*/
this.$router.onReady(() => this.routeLoaded());
},
template: `<router-view/>`
})
This will call the routeLoaded method every time the route changes (which I'm deducing is what you need since you are using the <router-view> element), if you also want to call it initially, I would recommend the mounted hook (like in the example) or the immediate flag on the watcher

In my opinion on this situation, you should use component life cycle method of the loaded component, either use mounted method or created method.
or if your script doesn't depend on any vue component (store) you can use router.afterEach hook
router.afterEach((to, from) => { if (to.name !== 'ROUTENAME'){ // do something }});

The solution for me was to set up a custom event in every page's mounted() hook with a mixin and listen for that event on the body for example. If you wanted to strictly tie it with the router's afterEach or the route watcher to ensure the route has indeed changed before the event was fired, you could probably set up a Promise in the afterEach and resolve it in the page's mounted() by either the event or sharing the resolve function through the window.
An example:
// Component.vue
watch: {
'$route': function (from, to) {
new Promise((resolve) => {
window.resolveRouteChange = resolve;
}).then(() => {
// route changed and page DOM mounted!
});
}
}
// PageComponent.vue
mounted() {
if(window.resolveRouteChange) {
window.resolveRouteChange();
window.resolveRouteChange = null;
}
}

In case of router-view, we can manually detect router-view.$el change after $route is changed
watch: {
'$route'(to, from) {
// Get $el that is our starting point
let start_el = this.$refs.routerview.$el
this.$nextTick(async function() { await this.wait_component_change(start_el)})
}
},
methods: {
on_router_view_component_changed: function() { }
wait_component_change: async function(start_el) {
// Just need to wait when $el is changed in async manner
for (let i = 0; i < 9; i++) {
console.log('calc_has_dragscroll ' + i)
if(start_el) {
if (!start_el.isSameNode(this.$refs.routerview.$el)) {
// $el changed - out goal completed
this.on_router_view_component_changed()
return
}
}
else {
// No start_el, just wait any other
if(this.$refs.routerview.$el) {
// $el changed - out goal completed too
this.on_router_view_component_changed()
return
}
}
await this.$nextTick()
}
},
}

You can accomplish this by hooking into VueJS lifecycle hooks:
Use VueJS Lifecycle Hooks:
Here is a summary of the major VueJS lifecycle hooks. Please consult the documentation for the full description.
i. beforeCreate: This function will be called before the component is created
ii. created: This function will be called after the component is created, but note although the component is created, it hasn't been mounted yet. So you won't be able to access the this of the component. However, this is a good place to make Network Requests that will update the data properties.
iii. mounted: This function is called once the component has been rendered and the elements can be accessed here. This is what you're looking for.
iv. beforeDestroy: This function is called before the component is destroyed. This can be useful to stop any listeners (setTimeout, setInterval..), that you created.
See the diagram below for the details.
const app = new Vue({
el: '#app',
router,
mounted(){
this.someFunction()
},
data: {
some data
},
template: `
<router-view/>
`
})
Use Vue Router Navigation Guards: Vue Router also expose some lifecycle hooks that can you hook into. However, as you will see below they do not fit your requirements:
i. beforeRouteEnter: called before the route that renders this component is confirmed. oes NOT have access to this component instance, because it has not been created yet when this guard is called!
ii. beforeRouteUpdate: called when the route that renders this component has changed, but this component is reused in the new route.
iii. beforeRouteLeave: called when the route that renders this component is about to be navigated away from.
References:
VueJS Documentation (LifeCycle): VueJS Instance
Vue Router Documentation (Navigation Guards): Navigation Guards

Related

Vue.js component method on creation

I'm new to Vue and I'd like to make an AJAX call every time my component is rendered.
I have a vue component lets say "test-table" and Id like to fetch the contents via an AJAX call. There are many such tables and I track the active one via an v-if/v-else-if etc.
Currently I have a cheaty solution: in the template for the component I call a computed property called getData via {{ getData }} which initiates the Ajax call but does only return an empty string. Id like to switch to the proper way but dont know how.
My code is like so: (its typescript)
Vue.component("test-table", {
props: ["request"],
data () {
return {
tableData: [] as Array<TableClass>,
}
},
template: `{{ getData() }} DO SOME STUFF WITH tableData...`,
computed: {
getData() : string {
get("./foo.php", this.request, true).then(
data => this.tableData = data.map(element => new TableClass(data))
)
return "";
}
}
}
HTML:
<test-table v-if="testcounter === 1" :request="stuff...">
<test-table v-else-if="testcounter === 2" :request="other stuff...">
...
get is an async method that just sends a GET request with request data to the server. The last parameter is only for saying the method to expect a JSON as answer. Similar to JQuerys getJSON method.
the "created" method does NOT work! It fires only one time when the component is first created. If I deactivate and activate again (with v-if) the method is not called again.
Btw: I'm using Vue 2.6.13
Lifecycle hooks won't fire every time if the component is cached, keep-alive etc
Add a console.log in each of the lifecycle hooks to see.
Change to use a watcher which handles firing getData again if request changes.
...
watch: {
request: {
handler: function() {
this.getData()
},
deep: true
}
},
created() {
this.getData()
},
methods: {
getData(): string {
// do request
}
}
#FlorianBecker try the lifecycle hook updated(). It may be a better fit for what you're trying to achieve. Docs here.
You should be able to use the mounted hook if your component is continuously rendered/unrendered using v-if, like so:
export default {
mounted() {
// do ajax call here
this.callAMethod();
},
...
}
Alternatively, you could use the created() hook but it is executed earlier in the chain, so this means the DOM template is not created yet so you cant refer to it. mounted usually is the way to go.
More info on these hooks can be found here.

vueJS mixin trigger multiple times in laravel 5.7

I am new in Vue jS [version 2]. There are 3 component in my page. I want to use a axios get data available in all pages. I have done as follows in my app.js
const router = new VueRouter({mode: 'history', routes });
Vue.mixin({
data: function () {
return {
pocketLanguages: [],
}
},
mounted() {
var app = this;
axios.get("/get-lang")
.then(function (response) {
app.pocketLanguages = response.data.pocketLanguages;
})
}
})
const app = new Vue({
router,
}).$mount('#app');
and using this pocketLanguages in a component like
{{ pocketLanguages.login_info }} this. Its working fine but My Issue is axios.get('') triggering 4 times when page load [in console]
Now how can I trigger this only once or anything alternative suggestion will be appreciated to do this if explain with example [As I am new in Vue]
You are using a global mixin, which means that every component in your app is going to make that axios get call when it's mounted. Since your page has several components in it, no wonder the call is being made several times. What you need to do here is either:
Create a normal mixin and only use it in the master/container/page component in every route that actually needs to fetch the data by providing the option mixins: [yourMixinsName]. That component can then share the data with the other components in the page.
If your data is common between pages then it's better to use a global store such as Vuex to simplify state management.
On a side note: It is usually better to handle your data initialization in the created hook. Handling it in the mounted hook can lead to some pitfalls that include repeated calls, among other things, due to parent/child lifecycle hooks execution order. Please refer to this article for more information on the subject.
Finally problem solved
In resources/js/components/LoginComponent.vue file
<script>
import translator from '../translation';
export default {
mixins:[translator],
beforeCreate: function() {
document.body.className = 'login-list-body';
},
.....
mounted() {
this.langTrans();
}
and my translation.js file at /resources/js
export default {
data: function() {
return {
pocketLanguages: []
};
},
methods: {
langTrans: function() {
var self = this;
axios.get('/get-lang')
.then(function (response) {
self.pocketLanguages = response.data.pocketLanguages;
});
}
}
};

Wait until parent component is mounted / ready before rendering child in vue.js

In my SPA app, I have an <app-view> wrapper which handles base app code (load user data, render navbar and footer, etc) and has a slot for rendering the actual page. This slot is rendered only if the user data is available.
This wrapper was created because some pages needed a different base code, therefore I couldn't keep this base code in the main app containing <router-view> anymore.
I tried looking if vue-router provides advanced options or suggests a design pattern for switching base code, didn't find anything.
The problem is that the child component will be rendered before the parent component is mounted, i.e. before the parent decides not to render the child component (because it's loading user data). This causes errors like undefined as no attribute foo.
Because of that, I'm looking for a way to defer child rendering until its parent is mounted.
I had a similar problem though not with a SPA. I had child components that needed data from the parent. The problem is that the data would only be generated after the parent has finished mounting so I ended up with null values in the children.
This is how I solved it. I used v-if directive to mount the children only after the parent has finished mounting. (in the mounted() method) see the example below
<template>
<child-component v-if="isMounted"></child-component>
</template>
<script>
data() {
isMounted: false
}, mounted() {
this.isMounted = true
}
</script>
After that, the child could get the data from the parent.
It is slightly unrelated but I hope it gives you an idea.
After trying a few options, it looks like I need to bite the bullet and explicitly define the data that my components depend on, like so:
<app-view>
<div v-if='currentProfile'>
...
</div>
</div>
(currentProfile is received from vuex store getter, and is fetched within app-view)
For any of you that wants to show the child component as soon as the parent components gets data from an API call then you should use something like this:
<template>
<child-component v-if="itemsLoaded"></child-component>
</template>
<script>
data() {
itemsLoaded: false
},
methods: {
getData() {
this.$axios
.get('/path/to/endpoint')
.then((data) => {
// do whatever you need to do with received data
// change the bool value here
this.itemsLoaded = true
})
.catch((err) => {
console.log(err)
})
},
},
mounted() {
this.getData()
// DONT change the bool value here; papa no kiss
this.itemsLoaded = true
}
</script>
If you try to change the boolean value this.itemsLoaded = true in the mounted() method, after calling the getData() method, you will get inconsistent results, since you may or may not receive the data before the this.itemsLoaded = true is executed.
You can actually put the v-if on the <slot> tag in your component.
new Vue({
el: '#app',
render: function(createElement) {
return createElement(
// Your application spec here
{
template: `<slotty :show="showSlot"><span> here</span></slotty>`,
data() {
return {
showSlot: false
}
},
components: {
slotty: {
template: `<div>Hiding slot<slot v-if="show"></slot>.</div>`,
props: ['show']
}
},
mounted() {
setTimeout(() => this.showSlot = true, 1500);
}
}
);
}
})
<script src="//unpkg.com/vue#latest/dist/vue.js"></script>
<div id="app">
</div>

call a function every time a route is updated vue.js

I have integrated intercom in my app and I need to call window.Intercom('update'); every-time my url changes.
I know I could add it on mounted() but I rather not modify all my component and do it directly using the navigation guards. (Mainly to avoid to have the same code in 10 different places.
At the moment I have:
router.afterEach((to, from) => {
eventHub.$off(); // I use this for an other things, here is not important
console.log(window.location.href ) // this prints the previous url
window.Intercom('update'); // which means that this also uses the previous url
})
This runs intercom('update') before changing the url, while I need to run it after the url changes.
Is there a hook which runs just when the url has changed?
How can I do this?
Thanks
Wasn't sure this would work as what you already have seems like it should be fine but here goes...
Try watching the $route object for changes
new Vue({
// ...
watch: {
'$route': function(to, from) {
Intercom('update')
}
}
})
I just came up with another solution beyond Phil's, you could also use Global Mixin. It merges its methods or lifecycle hooks into every component.
Vue.mixin({
mounted() {
// do what you need
}
})
created() {
this.$watch(
() => this.$route.params,
() => /*Your Function*/
);
},

Bind the vue to root element after plugin finishes ajax call

I am binding my application root element #app to vue and before that I am loading my custom plugin with Vue.use(myplugin). My plugin makes an ajax call, load the data and set it into Vue.$permission property.. so in short I want to load my user permission before mounting the app. but while my ajax call is fetching permission data, app is mounted and my page is getting rendered, which need the permission object.
is there a way I can bind the app root element to vue after my plugin finishes.. or any other alternate solution?
Yeah, that's quite simple actually:
const Vue = require('vue');
const vueInstance = new Vue({
// don't specify the 'el' prop there
});
doingAnAjaxCall() // assuming it returns a promise
.then(() => {
vueInstance.$mount('#root'); // only now the vue instance is mounted
});
If a Vue instance didn’t receive the el option at instantiation, it will be in “unmounted” state, without an associated DOM element. vm.$mount() can be used to manually start the mounting of an unmounted Vue instance.
See: https://v2.vuejs.org/v2/api/#vm-mount
So for your case you may use any asynchronous mechanism to detect the end of the ajax call. Maybe the simplest solution is to pass a callback function to your plugin object, and mount your vue instance inside.
/* Define plugin */
MyPlugin = {};
MyPlugin.install = function(Vue, options) {
doingAnAjaxCall()
.then(data => {
// do something with data
options.callback();
});
};
const Vue = require('vue');
/* Create the vue instance */
const vueInstance = new Vue({
// don't specify the 'el' prop there
});
/* Install the plugin */
Vue.use(MyPlugin, { // This object will be passed as options to the plugin install()
callback: () => {
vueInstance.$mount('#root'); // only now the vue instance is mounted
}
});

Categories

Resources