SoFunction
Updated on 2025-04-05

Two solutions to modify the style of external elements in vue component

In actual development, due to some irrationality in the design of the project at the beginning, it will be passed in the component

html[media=pad]{
     .xxx{
     /* Component style */
     }
}

The above method modifies the style of some components, which involves selecting from the html level, because I wrote the style tag like this

<style lang="less" scoped></style>

Therefore, the component cannot be modified or the external element of the component cannot be selected, so the style of the external element cannot be modified.

Solution:

Two types:

The first type:

Open a new global style tag directly

<style lang="less"></style>

Write global styles here

The second type:

Use :global

<style scoped>
:global(.red) {
  color: red;
}
</style>

Refer to the official documentation:/api/#scoped-css

vue dynamically changes the style of external elements of the component

It is mainly controlled through native js.

The main development object of vue is components. Everyone is familiar with internal control of components, but what about external components? For example, change the style of external elements of the component.

I encountered this kind of problem not long ago. There is a page that carries the map. But outside the page, there are navigation bars, breadcrumbs, and label bars, and a large area is occupied at the top. You know, the wide screen is now, and the size is pitiful in the vertical direction. As a map, the larger the area, the better. There is a lot of mess on the top now. The point is that these things are provided by the framework and do not provide any attributes for setting. what to do?

Mainly controlled by native js. Although vue has formulated some of its own syntax rules as a development framework, it still supports native js. For example, (), there is no problem in running such a statement in component methods. These statements are triggered when the page enters:

export default {
  components: {
    Map
  },
  beforeRouteEnter (to, form, next) { // Hide bread crumbs when entering this page    let bread = ('main-layout-tag-nav-wrapper')
    if ( &gt; 0) bread[0]. = 'none'
    next()
  },
  beforeRouteLeave (to, form, next) { // Recover bread crumbs when leaving this page    let bread = ('main-layout-tag-nav-wrapper')
    if ( &gt; 0) bread[0]. = ''
    next()
  }
}

This is the article about modifying the external element style of the component in the vue component. For more related content on modifying the external element style of the component, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!