selubamih
selubamih

Reputation: 83

How to remove stylesheet when changing page in Vue

As a beginner of Vue.js, I am trying to remove stylesheet which I added through the mounted lifecycle in a component with

 mounted() {
     this.style = document.createElement('link');
     this.style.type = "text/css";
     this.style.href = 'https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css';
     document.head.append(this.style);
 }

This works fine. When I visit this page, I can see the effect of the Bootstrap. However, when I change to another component through router-view, I want to remove this stylesheet to affect other pages. I tried remove like appending the stylesheet, but it doesn't work:

unmounted() {
    document.head.remove(this.style);
}

UPDATE
It seems that this works when I refresh the page or use $router.go(0) to refresh it but how can I remove the stylesheet without refreshing the page.

Upvotes: 2

Views: 4032

Answers (2)

tony19
tony19

Reputation: 138266

The HTMLLinkElement instance can be removed with .remove():

unmounted() {
    this.style.remove();
}

Upvotes: 0

bayoodavid
bayoodavid

Reputation: 43

you can try to disable it with this.style.disabled=true and don't do it in unmounted, since chances are good that there's no "this" as the component has been removed already. there's also a beforeUnmount or sth. like that.

Upvotes: 1

Related Questions