x10 c-fi
x10 c-fi

Reputation: 23

Completely separate styles based on route - Vue

I'm currently using a UI Library in main.js for all routes, but I want certain routes to be completely isolated from the UI Library and to have custom styles. How do I achieve this?

Upvotes: 0

Views: 846

Answers (1)

Dan Knights
Dan Knights

Reputation: 8368

You could use <style scoped> and for anything outside the scope of the component, use JS.

For example, if you only wanted the body to have a certain style for a certain route, you could add styles in the created hook and remove them in the beforeDestroy hook:

created() {
    document.getElementsByTagName("body")[0].style.padding = "20rem";
},
beforeDestroy() {
    document.getElementsByTagName("body")[0].style.padding = "0rem";
}

You could even create an entire stylesheet and append it to the head:

created() {
    const style = document.createElement("style");
    style.setAttribute("rel", "stylesheet");
    style.setAttribute("type", "text/css");
    style.innerHTML = "body { padding: 20rem }";
    document.getElementsByTagName("head")[0].appendChild(style);
},
beforeDestroy() {
    const head = document.getElementsByTagName("head")[0];
    head.removeChild(head.children[head.childElementCount - 1]);
}

Just make sure you cleanup properly when navigating from the route as you could end up leaving the stylesheet behind if, for example, head.children[head.childElementCount - 1] doesn't return the stylesheet you appended.

Upvotes: 2

Related Questions