I start the project with nuxt.js / express.
We have developed style scoped for each component (.vue) in nuxt.js. So, when routing , the property is overlaid on the same class name (style), so the page does not display properly.
1. What is the correct use of 'style scoped'?
2. Or should the routing process be <a> rather than <nuxt-link>?
What is the correct use of 'style scoped'?
The <style scoped></style> notation is not ambiguous, as the scoped attribute suggests, all the CSS elements defined within this scope apply only to the current component. If the CSS element exists globally, the scoped one -having the same name and type- takes precedence, that is, it overrides the globally defined CSS element.
For example, let us define in /components folder 3 components Component1.vue, Component2.vue, Component3.vue:
Component1.vue:
<template>
<div class="yellow-text">Component 1</div>
</template>
<script>
export default {
name: 'Component1'
}
</script>
<style>
.yellow-text {
color: yellow;
}
</style>
Component2.vue:
<template>
<div class="yellow-text">Component 2</div>
</template>
<script>
export default {
name: 'Component2'
}
</script>
<style scoped>
.yellow-text {
color: red;
}
</style>
Component3.vue:
<template>
<div class="yellow-text">Component 3</div>
</template>
<script>
export default {
name: 'Component3'
}
</script>
In Component1.vue, the text will be displayed in yellow.
In Component2.vue, the text will be displayed in red because the scoped CSS class takes precedence over the globally defined one in Component1.vue.
In Component3.vue, the text will be displayed in yellow.
So to respond to your question: there is no correct way because there is only one way to do that, and the meaning is not subject to any form of interpretation.
Or should the routing process be rather than ?
Even if <nuxt-link /> is rendered as <a href>, the documentation clearly states the former must be used to navigated through the Nuxt.js application and In the future, we will add features to the component, like pre-fetching on the background for improving the responsiveness of Nuxt.js Applications.
Related
I want to dynamically change the background-image on a ccs class in an imported component
How can I do that?
I have installed 'vue-range-slider' and have imported RangeSlider
The range-slider is set up the following way.
<template>
<div id="slider_div" >
<range-slider
class="slider"
min="0"
max="100">
</range-slider>
</div>
</template>
<script>
import RangeSlider from 'vue-range-slider'
import 'vue-range-slider/dist/vue-range-slider.css';
export default {
name: 'susScore',
data: function() {
return {
emoji: "../assets/emoji_small.jpg",
}
},
components: {
RangeSlider
}
</script>
<style >
#slider_div{
margin-top: 95px;
margin-left: 4%;
}
.slider{
width:200px;
}
.range-slider-knob {
background-image: url("../assets/emoji_small.jpg")
}
</style>
In this case I am sending a specific image but I want to send an image dynamically using the data option, emoji, in the component.
Question
How can I dynamically update the background-image in the imported .range-slider-knob class?
I tried using CSS variables in a previous question here on SO (Dynamically add image with css variable in vue) but got the reply that that wasn't possible
You can't use vm properties in <style> tag, but you can update emoji in data to:
emoji: require("../assets/emoji_small.jpg")
... and then pass it to any template element using:
<whatever :style={backgroundImage: `url(${emoji})`} />
A fully working example: codesanbox.
I combined require() with a computed changing loaded image based on slider value.
In the RangeSlider.vue file, line 13 shows that the component includes a named slot 'knob'. Vue Slots let you pass html/vue content into the component.
You could pass in a simple div on which you can dynamically change it's background using a method like #tao suggested. Note that a name attribute is given to match the name of the slot you are trying to replace; however, the name shouldn't be required because it is the only slot within component you are using.
<range-slider
class="slider"
min="0"
max="100">
<div
name="knob"
:style={backgroundImage: url(emoji)}
/>
</range-slider>
This method also gives you more freedom in how the knob is presented and/or manipulated with JS.
I have two .jsx files that represent their respective components.
The first one is, Blog.jsx
import React from "react";
import '../assets/css/blog.css';
export const Blog = () => (
<div>
<h1>Hello Blog</h1>
</div>
)
With its respective CSS file, blog.css
div { background: #ff481f; }
and the second one is, Landing.jsx
import React from "react";
import '../assets/css/landing.css'
export const Landing = () => (
<div>
<h1>Hello Landing</h1>
</div>
)
With its respective CSS file, landing.css
div { background: #86ff2b; }
I have added routing and called instances of those two components on the App.js file which is the default file of a React application. After running the application, when navigated to components, I faced a problem that the background color is the same for both of the components (It loads landing.css only and never changes).
How can I fix that problem that each component only uses its respective .css file and loads it?
By default webpack and other build tools will compile all CSS files into one, even if css was imported in separate JSX files. So you can't use different CSS files and expect you don't affect on another part of page.
You have some options:
Use BEM for naming class names.
Use cssModules. In this case elements will have their own css class name and styles will not affect any other elements except if you use :global selector.
css-module
Using html tags as css selectors is a bad practice (because there is the behaviour you describe).
You should use only css classes or inline styles (using id's is another bad practise, id's have high priority).
div {
width: 20px;
height: 20px;
}
#id {
background: red;
}
.class {
background: green;
}
<div id="id" class="class"></div>
In case using css classes there is the same problem (when you have two similar classes). And this case is decided using css modules (set of rules of building) or you can use css-in-js (external library) which has its pros and cons. Also you can use BEM (methodology) and if your application is not big you can avoid this trouble.
css modules will add to your classes random hash and instead .my-awesome-class-name you will get .my-awesome-class-name-dew3sadf32s.
So, if you have two classes .class in the first file and .class in the second file in the end you will get two classes .class-dew23s2 and .class-dg22sf and you styles will resolve as expected.
css-in-js is a similar way except you should write your styles using javascript with some profits like including only those styles that are needed at the moment (what you are looking for right now) and several others.
You can code using pure css / scss / postcss / etc but many companies already choose between css modules and css-in-js.
BEM is just naming conventions for your class names.
And lastly - if you use inline-styles using react you should remember:
{} is constructor of object and {} returns new object on every call, it's mean if you write something like:
class MyAwesomeComponent extends Component {
render() {
return <div style={{color: "red"}}></div>;
}
}
or
class MyAwesomeComponent extends Component {
render() {
const divStyles = {color: "red"};
return <div style={divStyles}></div>;
}
}
div will re-render every time your render will call because div takes new prop.
Instead, you should define your styles (for example) in outside of your class:
const divStyles = {color: "red"};
class MyAwesomeComponent extends Component {
render() {
return <div style={divStyles}></div>;
}
}
Don't define your css using HTML tags because it will affect your entire application.
use className,id or inline styling.
like- App.css
.myApp{ color: red;}
#myApp2{ color: blue;}
App.js
import './App.css'
<div className="myApp">color changed by className</div>
<div id="myApp2">color changed by id</div>
<div style={{color:'red'}}>color changed by inline object styling</div> // inline styling
This is not the best solution if you are looking forward to improve yours css imports/loads.
However could be the best solution if you dont want to go in deep in css, resolve the problem fast and keep working with HTML tag.
You can add a div for each component, define an Id for the div and wrap the component. Afterwards in the component's css fies you are going to define all the styles starting with the #id so all the css classe or HTML tag will affect just the corresponding component.
//App render in root
ReactDOM.render(
<App />,
document.getElementById('root')
);
//App
function App(props){
return [
<Blog />, <OtherComponent />
]
}
//Blog component
function Blog(props){
return <div id="blog">
<h1>I am Blog</h1>
</div>
}
//Other component
function OtherComponent(props){
return <div id="otherComponent">
<h1>Im am other component</h1>
</div>
}
/* blog.css*/
#blog h1{
color:yellow;
}
/* otherComponent.css*/
#otherComponent h1{
color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I am trying to modify the styling (colors) of existing class from the videojs Library.
I found that we can modify from css file. But I need to modify from the colour we get from react props, which is dynamic each time.
So, we have a class called vjs-control-bar coming from the videojs library to which we need to apply a color property with the value coming from react-props for eg. this.props.color. How we can achieve this ?
<div data-vjs-player>
<video ref={node => (this.videoNode = node)} className="video-js" />
</div>
The vjs-control-bar class wasn't here as it is coming from the video-js library
The right approach here would be to use one of those CSSinJS libraries and add rules that target the DOM elements that are rendered by the VideoJS library you are using.
Another alternative is to simply render a <style></style> tag in the component where you render the <video> component using the dangerouslySetInnerHTML prop.
Here is an example of how this might work:
function InnerComponent() {
return <h1 class="title">Text Color</h1>;
}
function App(props) {
return (
<div className="App">
<style
dangerouslySetInnerHTML={{
__html: `
.title {
color: ${props.color};
}
`
}}
/>
<h1>Hello CodeSandbox</h1>
<InnerComponent />
</div>
);
}
Here is sandbox - https://codesandbox.io/embed/white-star-9o897
Font Awesome is not working in my shadow DOM since I have the following in it to prevent styles from leaking in and out:
:host {
all: initial; /* 1st rule so subsequent properties are reset. */
display: block;
contain: content; /* Boom. CSS containment FTW. */
}
I'm able to use other stylesheets by just inlining them within the :host property, but that doesn't work with Font Awesome since it uses relative paths in its stylesheet.
I found this post and tried it with the scoped CSS I implement, but the icons show as squares, as can be seen in my example.
I had the same issue with StencilJS.
After hours of struggle and the answer from #Intervalia I was able to fix it.
The problem is that the browser doesn't load the font files when they are only included in the shadow dom (your custom web component). This means that the fonts also has to be included in the normal html file (aka light DOM) so that the browser can detect and load them in order to make them available in the shadow dom.
In my case I didn't use Font awesome instead it was a custom font but I tried it a second time with font awesome and a clean Stenciljs project. The solution is always the same doesn't matter which custom font you need.
Step 1: Move the font into your project. I created a seperate "assets" folder inside the "src" folder to have access from all the components. In this example I downloaded font awesome for web environment https://fontawesome.com/download. (I wouldn't recommend "npm install" since you have to use it in the index.html too)
Step 2: Prepare your web component (in this case my-component.tsx). You can import multiple css files using the styleUrls property. Just import the fontawesome css from your assets directory.
import { Component, Prop, h } from '#stencil/core';
#Component({
tag: 'my-component',
styleUrls: [
'my-component.css',
'../../assets/fontawesome/css/all.css'
],
shadow: true
})
export class MyComponent {
#Prop() first: string;
render() {
return <div> <i class="fas fa-question-circle"></i> </div>;
}
}
Step 3 prepare the file where you want to use the component (in this case index.html). The important line is the "link" tag. This includes the "font awesome css" again and force the Browser to really download the fonts.
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<title>Stencil Component Starter</title>
<link rel="stylesheet" type="text/css" href="./assets/fontawesome/css/all.css">
</head>
<body>
<my-component first="Stencil" last="'Don't call me a framework' JS"></my-component>
</body>
</html>
I know it feels wrong and looks weird but it is not enough to include font awesome only in the index html or in the web component. It must really be included in both files. That doesn't mean the Browser will load it multiple times - it will only be loaded once.
That means that you can't deliver the font with the web component - as far as i know. This isn't a stenciljs bug this is a general problem of the browsers. Please let me know if you have better solutions.
Just for fun here is a screenshot that shows that the browser doesn't load the fonts when it is only included in one file. http://prntscr.com/p2f9tc
Update 05.10.2019:
If you want to use your font inside your web-component the explanation above is correct and still necessary. But you can also use the slot tag inside the web-component. Than you automatically bypass the font from outside (the html) into the web-component. But notice it only works for the stuff you write between the tags of your web component.
That means you can use <my-component> <i class="your-font"/> </my-component>. In this case you don't have to import the font into the web components.
One thing I have noticed is that if the page does not load the CSS file then the shadowDOM won't load it either.
I really think that the only problem us that if the font is not defined on the page that it will not work in the component since the rest of the CSS seems to properly apply to the shadowDOM elements.
This example shows just the shadowDOM trying to load the CSS and it does not work:
let template = `
<style>
:host {
display: block;
}
</style>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<header>
<h1>DreamLine</h1>
<nav>
<ul>
<li>Tour</li>
<li>Blog</li>
<li>Contact</li>
<li>Error</li>
<li><i class="fa fa-search"></i> Search</li>
</ul>
</nav>
</header>
`;
class MyEl extends HTMLElement {
connectedCallback() {
this.attachShadow({mode: 'open'}).innerHTML = template;
}
}
customElements.define("blog-header", MyEl);
<i class="fa fa-battery-full" style="font-size: 45px;"></i>
<hr/>
<blog-header></blog-header>
<hr/>
And this example shows both the page and the shadowDOM loading it and it works:
let template = `
<style>
:host {
display: block;
}
</style>
<header>
<h1>DreamLine</h1>
<nav>
<ul>
<li>Tour</li>
<li>Blog</li>
<li>Contact</li>
<li>Error</li>
<li><i class="fa fa-search"></i> Search</li>
</ul>
</nav>
</header>
`;
class MyEl extends HTMLElement {
connectedCallback() {
const styles = document.querySelector('link[href*="fontawesome"]');
this.attachShadow({mode: 'open'}).innerHTML = template;
if (styles) {
this.shadowRoot.appendChild(styles.cloneNode());
}
}
}
customElements.define("blog-header", MyEl);
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<i class="fa fa-battery-full" style="font-size: 45px;"></i>
<hr/>
<blog-header></blog-header>
<hr/>
The code I like to use looks for the <link> tag I want in the body and then uses a clone of that tag inside the shadowDOM. This way my component is not out of sync. Yes, this can cause problems if the component was not expecting a change in the CSS but I find it works well for my projects.
If you don't need shadow: true then you can load the all.min.css directly via the index.html or the main application. Even loading the all.min.js file works.
If you need it within the shadow dom, then you need to load the all.min.css in index.html and also load it within shadow root using something like this.
`
componentDidLoad(): void {
this.hostElement.shadowRoot
.getElementById("some_Id")
.insertAdjacentHTML(
"afterbegin",
`<link rel="stylesheet" href="${getAssetPath(
"/fontAssets/fontawesome-free/css/all.min.css"
)}" />`
);
}
`
I wanted to share what I did for loading in Font Awesome icons to my stencil components (shadow enabled)...
After several hours into researching this topic, I think I've discovered a solution that will be the most efficient for my components to be bundled in a agnostic way and free of any additional style sheet includes in the HTML header.
My solution was to use the stencil-inline-svg module and then import the svg file directly from the Font Awesome module like this:
// the reference to the svg can be anything (searchIcon name).
// just make sure to import the correct svg from fontawesome node modules.
import searchIcon from 'fontawesome/svgs/regular/search.svg';
#Component({
tag: 'search-icon',
styleUrl: 'search-icon.scss',
shadow: true,
})
export class SearchIconComponent {
render(){
return (
{/* Not ideal to use innerHTML but this renders the full SVG markup */}
<span class="search-btn" innerHTML={searchIcon}></span>
)
}
}
Now, I can set css rules to modify the color and size of my icon like this
.search-btn {
width: 40px; // Set SVG size at the parent.
svg path {
fill: #fff; // Update svg path color.
}
}
Obviously this requires a little bit of Font Awesome icon knowledge so you know which icons to import.
Shadow Doms's style is scoped. And it does not interfere with outer style
FWIW I created a helper method to create a link for font-awesome at the parent page level. Not sure if this is in violation of any custom-elements/Web Components standards but I'll go ahead and post here in hopes that I'll be corrected :) It works for my use case w/ internal web applications for now though.
export const addFontAwesomeStyles = () => {
injectStylesheet("https://use.fontawesome.com/releases/v5.13.0/css/all.css");
injectStylesheet("https://use.fontawesome.com/releases/v5.13.0/css/v4-shims.css");
}
export const injectStylesheet = (href: string) => {
const links = document.head.querySelectorAll("link");
// Already been injected
for(let l in links)
if(links[l].href == href) return;
const link = document.createElement('link');
link.rel = "stylesheet";
link.href = href;
document.head.appendChild(link)
}
Then in your StencilJS component's construtor you can use it like so:
//...
constructor() {
addFontAwesomeStyles();
}
Let's save I have a .Vue component that I grab off of Github somewhere. Let's call it CompB and we'll add a single CSS rule-set there for a blue header:
CompB.Vue (a dependency I don't own, perhaps pulled from Github)
<template>
...
</template>
<script>
...
</script>
<style lang="scss" scoped>
.compb-header {
color: blue;
}
</style>
I plan to nest CompB into my own project's CompA. Now what are my options for overriding the scoped rule?
After playing around a bit, I think I've got a good approach.
Global overrides
For situations where I want to override the rules in all cases for CompB I can add a rule-set with more specificity like this: #app .compb-header { .. }. Since we always only have one root (#app) it's safe to use an ID in the rule-set. This easily overrides the scoped rules in CompB.
Parent overrides
For situations where I want to override both the global and scoped rules. Thankfully VueJS allows adding both a scoped and unscoped style block into a .Vue file. So I can add an even more specific CSS rule-set. Also notice I can pass a class into CompB's props since Vue provides built-in class and style props for all components:
// in CompA (the parent)
<template>
...
<!-- Vue provides built-in class and style props for all comps -->
<compb class="compb"></compb>
</template>
<script>
...
</script>
<style lang="scss">
#app .compb .compb-header {
color: red;
}
</style>
<style lang="scss" scoped>
...
</style>
(note: You can get more specific and make the class you pass into CompB have a more unique name such as .compa-compb or some hash suffix so there is no potential for collision with other components that use CompB and a class .compb. But I think that might be overkill for most applications.)
And of course CompB may provide its own additional props for adjusting CSS or passing classes/styles into areas of the component. But this may not always be the case when you use a component you don't own (unless you fork it). Plus, even with this provided, there is always those situations where you are like "I just want to adjust that padding just a bit!". The above two solutions seem to work great for this.
You will need to add more specificity weight to your css. You have to wrap that component in another class so you can override it. Here is the complete code
<template>
<div class="wrapper">
<comp-b>...</comp-b>
</div>
</template>
<script>
import CompB from 'xxx/CompB'
export default {
components: {
CompB
}
}
</script>
<style>
.wrapper .compb-header {
color: red;
}
</style>