can not get element by getElementById in beforeDestroy lifecycle vue - vue.js

I use document.getElementById in beforeDestroy lifecycle to get an element. But getElementById returns null. If I use ref, I can get the element. Is there any difference between them? Why document.getElementById can't get the element?

There is an issue with the timing and there could be many reasons for that.
But in your case , The ref was still in the virtual DOM object, which will be destroyed within the destroy event (Unlike the document template).
That would be one reason Vue recommends to use $refs if possible.

I had the same problem. I thought the beforeDestroy hook was the right place to kill event listeners before leaving the component. For my surprise, when the route changes, the component is already unmounted when this hook is called.
This is vue.js version 2, I don’t know if it is better in version 3.

Related

removing event listeners in Nuxt/Vue

I'm on Nuxtjs 2.13 and i wanna know "how should I remove event listeners (is there a need??)".
I'm not talkinkg about js addEventListener and removeEventListener . I'm more curious about this.$emit() , $nuxt.$emit() and $nuxt.$on() . is there a way to remove $nuxt.$on() or listener on component <mycomp #myevent="do()" /> in beforeDestroy() and is it necessary?
as my Nuxt project using so much RAM on my server, i kindda think there are some optimization needed.
https://v3.vuejs.org/api/options-lifecycle-hooks.html#unmounted
When this hook (unmounted - OP) is called, all directives of the component instance have been unbound, all event listeners have been removed, and all child component instance have also been unmounted.
However, there is vm.$off which can
Remove custom event listener(s).
https://v2.vuejs.org/v2/api/#vm-off
I saw it used here in a Nuxt context to remove $nuxt.$on listeners:
https://medium.com/#aneesshameed/event-bus-in-nuxt-7728315e81b6
So, if need be, use $nuxt.$off to remove custom events in Nuxt.

keep-alive doesn't cache component

I have issue with having keep-alive actually keeping components alive.
Component that is being rendered in router-view have async fetching after component is mounted. My issue is that after the first time component shows up, when I render other component in that very same router, and then go back, then first component rerender as normal instead of keeping fetched data as it was.
I checked hooks and besides activated and deactivated also created hook fires which I suppose shouldn't be the case beyond first render. Also when I switch components destroyed hook fires which also shouldn't happen.
.container-fluid
.row.wrapper
aside.col-12.col-sm-2.p-0
nav.navbar.navbar-light.navbar-expand-sm.align-items-start.flex-sm-column.flex-row.text-uppercase#navbar1
a.navbar-toggler(href='', data-toggle='collapse', data-target='.sidebar')
span.navbar-toggler-icon
.collapse.navbar-collapse.sidebar
ul.flex-column.navbar-nav.w-100.justify-content-between
li.nav-item
router-link.nav-link.pl-0(to='candidates' data-toggle="collapse" data-target=".navbar-collapse.show")
font-awesome-icon.fa-fw.mr-2(:icon="iconTachometer")
| Dashboard
main.col.bg-faded.py-3
.card
.card-body
keep-alive
router-view(:key="$route.fullPath")
Okay, I found the answer - and my apologies because turned out my question wasn't fully informed.
First thing - the component in question was already nested within another router-view so what I was actually doing was nesting one in another.
Therefore, to keep alive that nested/child router-view parent router-view also has to be wrapped with keep-alive.
Based on answer here: https://forum.vuejs.org/t/how-to-use-keep-alive-with-nested-router-component/46813/4
See Special Attributes - key:
It can also be used to force replacement of an element/component
instead of reusing it. This can be useful when you want to:
Properly trigger lifecycle hooks of a component;
Trigger transitions.
If you bind key to $route.fullPath, it will always force a replacement of the <router-view> element / component every time a navigation event occurs. So just remove :key.

Default-expand-all doesn't work for q-tree? Vue.Js

I have to code a web application and the most important element is the q-tree. I'm already able to load and show data (passing an array called list), but I want that all nodes are expanded.
The vue.js examples of the official documentation show that you're be able to do this with the 'default-expand-all' attribute but this isn't working for me.
It only shows me the root node with an arrow, where I have to expand the children nodes manually.
<q-tree
:nodes="list"
:selected.sync="selected"
#update:selected="onSelectionChangedNode"
node-key="NodeNr"
label-key="NodeTxt"
default-expand-all
></q-tree>
Taking a cue from the accepted answer, I realised that the dom has already been created with the tree component on first render.
In my use case, I want to update the Tree when data comes back from the server.
So, I had to force it to re-render with the expanded functionality using:
this.$nextTick(function () {
this.$refs.nodes.expandAll();
})
The nextTick function will update the dom in the next window of execution, by which time the nodes will get expanded by calling the expandAll function.
And NB: For those confused by the astericks on the ref attribute or how to add it to the component, here goes:
<q-tree :nodes="list"
:selected.sync="selected"
#update:selected="onSelectionChangedNode"
node-key="NodeNr"
label-key="NodeTxt"
ref="nodes"
>
Solved my problem as following:
I have added a ref attribute to the QTree DOM Element which makes it possible to access predefined methods of QTree API.
<q-tree
:nodes="list"
:selected.sync="selected"
#update:selected="onSelectionChangedNode"
node-key="NodeNr"
label-key="NodeTxt"
**ref="nodes"**
>
The function I have been using is expandAll().
updated() {
this.$refs.nodes.expandAll();
}
The most important thing for me was, I had to find out which lifecycle hook was the right one for me. The update() hook was the one I was looking for.
The reason:
Called after a data change causes the virtual DOM to be re-rendered and
patched.
The component’s DOM will have been updated when this hook is called, so you
can perform DOM-dependent operations here.
The default-expand-all is only applied on the first rendering of that Component.
So if your Component renders when the nodes aren't assigned they wont expand if assigned afterwards.
https://v1.quasar-framework.org/vue-components/tree
You have to work with scoped slots and an expanded attribute if you dont have the nodes on first rendering.

What's the Vue lifecycle chronology between components?

Let's say I have a <router-view> showing one component (A) and through a <router-link> this component will be replaced by another one (B).
Both components have their own beforeCreate and beforeDestroy hooks. I'd expect that if I navigated from A to B the sequence of events would be:
A.beforeDestroy
B.beforeCreate
But after doing some tests it appears to be the exact opposite: B.beforeCreate is always called before A.beforeDestroy.
Is that correct? And if it's correct, why is it this way? Doesn't make sense to me...
In my case all those hooks interact with some common data, so I'm facing race conditions here... Any suggestion on how to deal with that? I need to get some things done before creating B that cannot be started before destroying A...
Before the previous component is destroyed, the next component will be created first.
The purpose is obviously to avoid flickering as the view transitions from the previous component to the next component.
If the behavior you wanted is to make sure that a code should be executed always after the beforeDestroy and not before, you should use the mounted or beforeMount lifecycle hook.

Invoke method in child component when the component is changed dynamically from the parent component

I have a simple component hierarchy, in which there is one parent component, which contains the following template <div><component :is="current"></component></div> and two child components, which are dynamically 'switched' out, via the value of current.
The logic for the 'switching' of components is being handled in the parent component. However, when I try to execute a method in the second child component (in response to an event emitted from the first child component, being listened to in the parent component, and altering the value of current in the parent component) through the mounted lifecycle hook, the expected result is not observed.
Essentially, I cannot find a decent way of invoking a child component's methods when that component is 'switched' in as the current component in the parent component.
I have realistically looked at using the $refs and $childrenproperties on the instance, but these do not seem to be of any assistance. I have also reasoned using the event system. I usually 'define' an event listener in the mounted lifecycle hook, however, I refer to the 'issue' of using the lifecycle hooks
What is the usual approach to this situation?
There are two options that immediately come to mind for child components invoking methods on being the "current" child component:
1) Using the mounted lifecycle hook. In order for this to work, you must be using v-if in order to conditionally display the child component, otherwise the child component will not trigger the mounted lifecycle hook. Otherwise, if you're using v-show or some other mechanism for conditionally displaying the child component, the mounted hook will only ever trigger once.
2) Using watched properties. In lieu of the above, you could do something like the following:
<child-component :target_prop="current"></child-component>
Vue.component('child-component', {
. . .,
props: ['target_prop'],
watch: {
target_prop: function() {
if(this.target_prop == your_expected_value) {
//execute the desired method for this component
}
}
}
});
This is, of course, just a proof-of-concept example and there are plenty of alternative ways to use the watched properties to your advantage.
I've also heard of using a "bus" to handle inter-component communication, but I don't believe it would be any better than the above two solutions (and is arguably worse).
Personally, I prefer the mounted lifecycle hook approach, though there's the caveat that any "settings" or data in your child components will be lost on switching between them (although you could also emit a settings object on destruction and store/restore those settings as needed, but that could get messy). You'll have to make the final judgment on which approach better suits your needs and which consequences you're more comfortable dealing with.