2

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.

tony19
  • 125,647
  • 18
  • 229
  • 307
selubamih
  • 83
  • 3
  • 15
  • My first thought was instead of building the stylesheet link tag at runtime, possibly binding Vue to a link tag in the head section, which I haven't done. After a brief search, I found this [SO question](https://stackoverflow.com/questions/36612847/how-can-i-bind-the-html-title-content-in-vuejs) which may be applicable. Possibly you could add/remove the href value. – Tim Feb 14 '21 at 16:31

2 Answers2

1

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.

bayoodavid
  • 43
  • 5
0

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

unmounted() {
    this.style.remove();
}
tony19
  • 125,647
  • 18
  • 229
  • 307