Vue: What is the cleanest way to select a component via CSS?

落花浮王杯 提交于 2019-12-07 08:30:27

问题


I have a bar component. It is used like this:

<template>
  <div>
    <!-- stuff -->
    <bar></bar>
    <!-- stuff -->
    <!-- stuff -->
    <!-- stuff -->
    <bar></bar>
    <!-- stuff -->
    <bar></bar>
    <!-- stuff -->  
  </div>
</template>

<style lang="scss" scoped>
  @media (max-width: 1300px) {
    // this selector doesn't work, but it would be nice if it did
    bar {
      display: none;
    }
  }
</style>

I would like to hide the bar elements when the screen is 1300px or narrower. It would be nice if there was a bar element selector, just like there are p and h1 element selectors. However, there doesn't seem to be, and I have to add class="bar" in order to select them.

My question is if there is a cleaner way to select the bar elements.

It wouldn't be good to add the CSS code inside of the bar component because when the bars are used inside of other components, I don't want to hide them at all.


回答1:


A class seems to be the best way to go. Put it on the root element of the component if you want it to be universal for the component, or only on the component tag if you want it to be specific to that use.

Also, there is no reason you couldn't use a custom tag as the root element of your component; as long as the tag didn't map to a component, it would be left in the DOM, and you could use it for CSS selection. I don't recommend it, though, as I don't think this use case is a good reason for introducing a new tag.

If your component template looked like this, for example:

<template>
  <bar-container>
    Hi there
  </bar-container>
</template>

and you had no bar-container component defined, you would be able to use CSS to select bar-container, which would be the container element for every bar component. But it's just as easy to use <div class="bar-container"> instead.




回答2:


After better understanding the problem at hand, would this work?

<div class="someClass">
    <bar v-bind:width="draw.probability" type="draw" ref="myComponent"></bar>
</div>


来源:https://stackoverflow.com/questions/48287567/vue-what-is-the-cleanest-way-to-select-a-component-via-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!