This time I will bring you an analysis of the steps for using scoped in Vue. What are the precautions for using scoped in Vue? The following is a practical case, let’s take a look.
What is scoped?
On the style tag in the vue file, there is a special attribute: scoped. When a style tag has a scoped attribute, its CSS style can only be applied to the current component, that is, the style can only be applied to the current component element. Through this attribute, the styles between components can be prevented from contaminating each other. If all style tags in a project are scoped, it is equivalent to realizing themodularization of the style.
The implementation principle of scoped
The effect of the scoped attribute in vue is mainly achieved through PostCSS translation. The following is the vue code before translation:<style scoped> .example { color: red; } </style> <template> <p class="example">hi</p> </template>
<style> .example[data-v-5558831a] { color: red; } </style> <template> <p class="example" data-v-5558831a>hi</p> </template>
CSS selector The Attribute selector is used to select the dom in the component. This approach makes the style only apply to the dom containing the attribute - the internal dom of the component.
Why do we need to penetrate scoped?
scoped looks beautiful, but in many projects, there will be a situation where<style scoped> 外层 >>> 第三方组件 { 样式 } </style>
A curved method to save the country
In fact, there is also a curved method to save the country, that is, after defining a style tag containing a scoped attribute In addition, define a style tag that does not contain the scoped attribute, that is, define a global style tag in a vue component, and a style tag with a scope:<style> /* global styles */ </style> <style scoped> /* local styles */ </style>
Personally recommended method
The above two methods, the penetration method actually violates the meaning of the scoped attribute, and the curve-saving method also It makes the code too ugly. I personally recommend the third method, that is: because scoped looks beautiful, but it contains a lot of pitfalls, so it is not recommended not to use the scoped attribute, but to distinguish the differences by adding a unique class to the outer dom components. This method not only achieves an effect similar to scoped, but also facilitates modifying the styles of various third-party components, and the code looks relatively comfortable. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:Detailed explanation of the steps to build a react development environment with webpack
Detailed explanation of the steps to install and delete npm modules
The above is the detailed content of Scoped usage step analysis in Vue. For more information, please follow other related articles on the PHP Chinese website!