search
HomeWeb Front-endJS TutorialHow to use the scoped attribute of style in vue

This article mainly introduces the scoped attribute of style used with caution in Vue. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

In the vue component, in order to privatize (modularize) the style and not pollute the global situation, you can add the scoped attribute to the style tag to indicate that it only belongs to the current moment. Modules, this is a very good move, but why should it be used with caution? Because when we need to modify the style of public components (third-party libraries or project-customized components), scoped often causes more difficulties and requires additional complexity.

The principle of scoped implementation of privatized styles

Why do you think it will increase complexity? So let's start with the principles of implementing modules. For convenience of naming, we assume that this kind of component is called module private component, and other unscoped components are called module general components.

By looking at the DOM structure, we found that vue adds unique and non-repeating tags to the DOM structure and css style to ensure uniqueness and achieve the purpose of privatizing and modularizing the style. The specific rendering result is explained through an example.

Public component button component

A public component button, in order to modularize the style, add the scoped attribute to it,

//button.vue
<template>
  <p class="button-warp">
    <button class="button">text</button>
  </p>
</template>
...
<style scoped>
  .button-warp{
    display:inline-block;
  }
  .button{
    padding: 5px 10px;
    font-size: 12px;
    border-radus: 2px;
  }
</style>

Browse The browser renders the button component

The html part and css part rendered by the button component in the browser are:

<p data-v-2311c06a class="button-warp">
  <button data-v-2311c06a class="button">text</button>
</p>
.button-warp[data-v-2311c06a]{
  display:inline-block;
}
.button[data-v-2311c06a]{
  padding: 5px 10px;
  font-size: 12px;
  border-radus: 2px;
}

As can be seen from the above words, the component with the scoped attribute added , in order to achieve modularization of component styles, two processes were done:

  1. Add a non-repeating data attribute (in the form: data-v-2311c06a) to the HTML DOM node to represent it Uniqueness

  2. Add a data attribute selector of the current component (such as [data-v-2311c06a] at the end of each css selector (compiled and generated css statement) ) to privatize styles

Everyone knows that CSS styles have a priority. Although the operation of scoped achieves the purpose of modularizing component styles, it will cause a Consequences: The weight of each style is increased: in theory, if we want to modify this style, a higher weight is needed to cover this style. This is one of the dimensions that adds complexity.

Other components reference the button component

The above analyzes the result of a single component rendering, so what will be the result after the components call each other? , specifically divided into two situations: module general components refer to module private components (essentially the same as module private components refer to module general components); module private components refer to module private components.

For example: If the button component is used in the component content.vue, what is the difference in the rendering result whether the content.vue component adds the scoped attribute?

//content.vue
<template>
  <p class="content">
    <p class="title"></p>
    <!-- v-button假设是上面定义的组件 -->
    <v-button></v-button>
  </p>
</template>
...
<style>
  .content{
    width: 1200px;
    margin: 0 auto;
  }
  .content .button{
    border-raduis: 5px;
  }
</style>

The general components of the module (not scoped) refer to the private components of the module

If the scoped attribute is not added to the style, then the rendered html and css are:

<p class="content">
  <p class="title"></p>
  <!-- v-button假设是上面定义的组件 -->
  <p data-v-2311c06a class="button-warp">
    <button data-v-2311c06a class="button">text</button>
  </p>
</p>
/*button.vue渲染出来的css*/
.button-warp[data-v-2311c06a]{
  display:inline-block;
}
.button[data-v-2311c06a]{
  padding: 5px 10px;
  font-size: 12px;
  border-radus: 2px;
}
/*content.vue渲染出来的css*/
.content{
  width: 1200px;
  margin: 0 auto;
}
.content .button{
  border-raduis: 5px;
}

Yes It can be seen that although the border-raduis attribute of the button is modified in the content component, due to the weight relationship, the style inside the component still takes effect (at this time, the external style is overwritten). So if we want to achieve the purpose of modifying the style, we must increase the weight of the style we want to modify (increase selector level, ID selector, parallel selector, important, etc.)

Module private components (add scoped ) Reference module private components

What if the scoped attribute is added? According to the rules analyzed at the beginning (this is also true):

First add the data attribute to all DOM nodes

Then add the data attribute selector at the end of the css selector

Then the rendered html and css are:

<p data-v-57bc25a0 class="content">
  <p data-v-57bc25a0 class="title"></p>
  <!-- v-button假设是上面定义的组件 -->
  <p data-v-57bc25a0 data-v-2311c06a class="button-warp">
    <button data-v-2311c06a class="button">text</button>
  </p>
</p>
/*button.vue渲染出来的css*/
.button-warp[data-v-2311c06a]{
  display:inline-block;
}
.button[data-v-2311c06a]{
  padding: 5px 10px;
  font-size: 12px;
  border-radus: 2px;
}
/*content.vue渲染出来的css*/
.content[data-v-57bc25a0]{
  width: 1200px;
  margin: 0 auto;
}
.content .button[data-v-57bc25a0]{
  border-raduis: 5px;
}

For the above two situations, it can be clearly seen that the results after rendering are very different.

Although we have added code in content that wants to modify the style of the button component, but look carefully, since the .content .button sentence is added at the end with the scoped tag of the content component, the last sentence actually has the fundamental effect It is not on the DOM node we want, so in this case any styles we write inside the content will not affect the button.vue component, so this is embarrassing. . . .

Of course, this problem can also be solved, that is, directly adding global styles can be modified, but this will inevitably affect the components in all places; so another method is needed to add a new one in the content.vue component without The style tag of the scoped attribute means adding two styles, one for private styles and one for public styles. This is definitely a bit shit, and both solutions cannot avoid one problem: weight! ! !

//content.vue
<template>
  <p class="content">
    <p class="title"></p>
    <!-- v-button假设是上面定义的组件 -->
    <v-button></v-button>
  </p>
</template>
...
<style scoped>
  .content{
    width: 1200px;
    margin: 0 auto;
  }
</style>
<style>
  .content .button{
    border-raduis: 5px;
  }
</style>

Is this in compliance with the regulations? It seems that I didn't see that I couldn't write it like this, and it did take effect. . . But this does increase the complexity of thinking, which is a bit distressing.

Summary the rendering rules of scoped

Summary the three rendering rules of scoped

  1. Add a non-duplicate to the DOM node of HTML data attribute (form: data-v-2311c06a) to express its uniqueness

  2. Add a data attribute selector of the current component (such as [data-v-2311c06a]) to the end of each css selector (compiled and generated css statement) to privatize the style

  3. If the component contains other components, only the data attribute of the current component will be added to the outermost tag of other components

Solution

For the referenced third-party library, if the other party uses scoped, we cannot change anything. If we really need to modify its style, we can best modify the style in the component without scoped, or globally Modifying the style directly is very rude!

For the components you maintain, you must think clearly whether the style of the component can meet all situations. If it is really necessary to add it, it will undoubtedly increase the work of the developers who use this component!

Of course, if you have a better solution to this problem, please TELL ME!

Fun facts

When using scoped, you must be careful about this feature of scoped. I thought this was a BUG, ​​so I raised an issue > ;, As a result, Youda replied very domineeringly
The original intention of scoped design is not to allow the style of the current component to modify the style of any other place, because the design is like this. So of course this issue has been closed

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

About crypto module security knowledge in Nodejs (detailed tutorial)

How to achieve blurred drop-down box in Angular Query function

How to implement login in js that requires sliding verification

The above is the detailed content of How to use the scoped attribute of style in vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools