Switching between Vue Router pages cause multiple event fire on VueJS mounted() - javascript

I am working on an Electron project where I use Vue CLI project and the Vue CLI Plugin Electron Builder. Everything works great except a weird bug that I found recently.
Whenever I navigate between pages (Vue Router), the event I listen for from the component mounted() property becomes double. It's actually the N+1 issue.
to describe the issue more clearly, I have two Home.vue and HelloWorld.vue components. From Home.vue component, I am sending an event to the main process whenever clicking a button and listening the event.reply() from the same component mounted() property. It's completely as expected at this stage.
However, whenever I go to the HelloWorld page and switch back to the Home page again and when I click the button to send and receive the event from the main process, I don't only see a single event even though I click one time only but I see two event reply. If I switch between pages again, I'll see three event reply and so on like N+1 issue.
For your convenience, I made a quick GIF that will show the issue clearly.
Home.vue
<template>
<div class="home">
<button #click="send()">Home</button>
</div>
</template>
<script>
export default {
name: "Home",
data() {
return {
cause: null
}
},
mounted() {
window.ipcRenderer.on("home:reply", event => console.log(event));
},
methods: {
send() {
window.ipcRenderer.send("home");
}
},
};
</script>
main.js
ipcMain.on("home", event => {
return event.reply("home:reply");
});
I don't have anything special on the Vue Router and it's just default scaffolding that comes with the Vue CLI. As you can see in the above code snippet, all I am doing is just sending an event when clicking a button and listening for the same event reply from the same component mounted() property.
I also found a similar topic on Stack Overflow but couldn't figure it out myself. I have no clue what's wrong on my code 🥱

You need to unregister the event handler when the component is destroyed, otherwise you'll just keep registering the same event handler again and again each time the component is mounted.
mounted() {
window.ipcRenderer.on('home:reply', this.handleHomeReply)
},
destroyed() {
window.ipcRenderer.off('home:reply', this.handleHomeReply)
},
methods: {
handleHomeReply(event) {
console.log(event)
}
}

Related

Navigating back causes change detection to break in Angular elements

I am using Angular elements to use my components inside of custom ThingsBoard widgets. The elements are created inside ngDoBootstrap() like this:
const newCustomElement = createCustomElement(CustomElementComponent, {
injector: this.injector,
});
customElements.define("new-custom-element", newCustomElement);
In a ThingsBoard widget I can then import the compiled JavaScript code of my elements via the "Ressources" tab and instantiate them in the onInit() function of the widget like this:
self.onInit = function() {
element = document.createElement(
"new-custom-element");
self.ctx.$container.append(element);
}
While this works just fine and enables me to use Angular components in my widgets, I noticed a strange problem which sometimes occurs when navigating from a ThingsBoard dashboard state back to another dashboard state. Sometimes after navigating back, my widget would seem to load just fine but then the entire change detection seems to be broken. As long as I do not manually call detectChanges() in my component, the component will sometimes appear to freeze entirely in the UI and no longer react to any user interaction (such as a click event). Only refreshing the page will fix this problem.
What could cause this problem and is there anything I can do in order to fix this?
Have you ever tried like this:
ngAfterViewChecked() {
this.cd.detectChanges();
}
or
constructor(private appRef: ApplicationRef) { }
ngAfterViewInit() {
this.appRef.bootstrap(CustomElementComponent);
}
Good luck.

How to make pagination and content render on browser back button in Vue cli?

I am trying to make in Vue.js CLI table with pagination and pages I have API backend and everything.
Now I have URL with "?page=1" and I want when I click on browser back button my table and pagination render on the same page what is URL. Right now on browser back button only URL change but the content stays the same.
But I hear there is a global fix with Vue router for that does anyone know how to do that?
I'm not sure if this is what you are talking about, but in this vue school video they talk about the Vue Router not always picking up on changes if the same component is being used. You can handle it by adding a key to the router-view with value $route.path. Then any change to the path will trigger a reload of the component.
You could put a watcher on the route:
computed : {
page () {
return this.$route.params.page
}
},
watch : {
page (val) {
updateContent(val)
}
},
mounted () {
updateContent(this.page)
}

Where to call addListener in react native

We are working on React Native project. In that, We are showing tabbar in that and also sidebar too.
So, for that side bar we added react-navigation library. But, In, Android, If user tap on that device's back button, if the drawer is opens, We have to close it.
So, We are adding addListener in componentDidMount() and removing it in componentWillUnmount().
But, The issue is, If I switch to another tab and come back to previous tab, And if we tap on device back button, The back button handler not calling due to listener is removed.
Is there any alternative which method will call always once we switched to previous screen.
We know, componentDidMount only will call once while launching time of that screen.
We know we can call render method, But, We are expecting to call it in with good practice.
And is there any way to make it global way instead of writing call the
classes closing drawer.
Code:
componentDidMount() {
BackHandler.addEventListener('backTapped', this.backButtonTap);
}
componentWillUnmount() {
BackHandler.removeEventListener('backTapped', this.backButtonTap);
}
backButtonTap = () => {
navigation.dispatch(DrawerActions.closeDrawer());
}
Any suggestions?
I would suggest to use react-navigation's own Navigation Lifecycle listener, so you can also handle different back button behaviour on different page.
componentDidMount() {
this.willFocusListener = navigation.addListener('willFocus', () => {
BackHandler.addEventListener('backTapped', this.backButtonTap);
});
this.willBlurListener = navigation.addListener('willBlur', () => {
BackHandler.removeEventListener('backTapped', this.backButtonTap);
});
}
componentWillUnmount() {
this.willFocusListener.remove();
this.willBlurListener.remove();
}
Then NavigationEvents component could be helpfull too

How to create multiple Vue components inside of Bootstrap tabs?

I am using the togglable tabs component in Bootstrap. I would like a table in each tab. Each one is displaying a table of email logs (Click Event, Open Event, etc). I would also like each table to be loaded dynamically with Vue-resource only once the user clicks on that tab, and for the resource/component to only be loaded once (once we have the data from AJAX, don't refresh it).
How can I set this up? I currently have an email-table component and an email-table-template template that renders the table, but I'm not sure how to set those up to render themselves when the user clicks the tab, and to only call the AJAX once.
An illustration of the task
Here is my current code for detecting the tab switch and newing up a Vue component:
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var email_event = $(e.target).data('email-event');
switch(email_event) {
case 'click':
createClick();
break;
// rest of the cases
}
function createClick() {
var click_events = Vue.resource('/api/email_logs/click_events');
click_events.get().then((response) => {
new Vue({
el: '#table-click',
data: {
searchQuery: '',
gridColumns: ['campaign_id', 'target_link_name', 'target_link_url', 'created_at'],
gridData: response.body
}
})
});
Any insight is appreciated. Thanks very much!
If you want to call a method only once you can use listen and emit events.
vm.$once and vm.$emit should do the trick.
Official documentation
https://v2.vuejs.org/v2/api/#vm-once
Here is a quick example
https://jsfiddle.net/leocoder/s1nfsao7/4/
From official documentation
If you want to keep the switched-out components in memory so that you can preserve their state or avoid re-rendering, you can wrap a dynamic component in a <keep-alive> element
Sample:
<keep-alive> <component :is="currentView"> <!-- inactive components will be cached! --> </component> </keep-alive>
In the above example "currentView" is to be set to a component name you want to load/display
Docs: https://v2.vuejs.org/v2/api/#keep-alive

Vue.js Router: Run code when component is ready

I'm working on a single-page app with Vue.js and its official router.
I have a menu and a component (.vue file) per every section which I load using the router. In every component I have some code similar to this:
<template>
<div> <!-- MY DOM --> </div>
</template>
<script>
export default {
data () {},
methods: {},
route: {
activate() {},
},
ready: function(){}
}
</script>
I want to execute a piece of code (init a jQuery plugin) once a component has finished transitioning in. If I add my code in the ready event, it gets fired only the first time the component is loaded. If I add my code in the route.activate it runs every time, which is good, but the DOM is not loaded yet, so is not possible to init my jQuery plugin.
How can I run my code every time a component has finished transitioning in and its DOM is ready?
As you are using Vue.js Router, it means that each time you will transition to a new route, Vue.js will need to update the DOM. And by default, Vue.js performs DOM updates asynchronously.
In order to wait until Vue.js has finished updating the DOM, you can use Vue.nextTick(callback). The callback will be called after the DOM has been updated.
In your case, you can try:
route: {
activate() {
this.$nextTick(function () {
// => 'DOM loaded and ready'
})
}
}
For further information:
https://vuejs.org/api/#Vue-nextTick
https://vuejs.org/guide/reactivity.html#Async-Update-Queue
You can use
mounted(){
// jquery code
}
Though this may be a bit late... If I guess correctly, the component having problem stays on the page when you navigate between routes. This way, Vue reuses the component, changing what's inside it that needs to change, rather than destroy and recreate it. Vue provides a key attribute to Properly trigger lifecycle hooks of a component. By changing a component's key, we can indicate Vue to rerender it. See key in guide for details and key in api for code sample.

Categories

Resources