Vue: What is the cleanest way to select a componen

2019-05-23 12:25发布

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.

2条回答
ら.Afraid
2楼-- · 2019-05-23 12:46

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>
查看更多
来,给爷笑一个
3楼-- · 2019-05-23 13:09

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.

查看更多
登录 后发表回答