Vue:通过 CSS 选择组件最简洁的方法是什么?

Vue: What is the cleanest way to select a component via CSS?(Vue:通过 CSS 选择组件最简洁的方法是什么?)

本文介绍了Vue:通过 CSS 选择组件最简洁的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 bar 组件.它是这样使用的:

<模板>

<!-- 东西--><酒吧></酒吧><!-- 东西--><!-- 东西--><!-- 东西--><酒吧></酒吧><!-- 东西--><酒吧></酒吧><!-- 东西--></div></模板><style lang="scss" 作用域>@media(最大宽度:1300px){//这个选择器不起作用,但如果它起作用就好了酒吧 {显示:无;}}</风格>

我想在屏幕为 1300 像素或更窄时隐藏条形元素.如果有一个 bar 元素选择器就好了,就像有 ph1 元素选择器一样.但是,似乎没有,我必须添加 class="bar" 才能选择它们.

我的问题是是否有更简洁的方法来选择 bar 元素.

bar 组件内部添加 CSS 代码并不好,因为当 bar 用于其他组件内部时,我 不'根本不想隐藏它们.

解决方案

上课似乎是最好的方法.如果您希望它对组件通用,则将其放在组件的根元素上,或者如果您希望它特定于该用途,则仅放在组件标签上.

此外,您没有理由不能使用自定义标签作为组件的根元素;只要标签没有映射到组件,它就会留在 DOM 中,您可以将其用于 CSS 选择.不过我不推荐它,因为我认为这个用例不是引入新标签的好理由.

如果你的组件模板看起来像这样,例如:

<模板><酒吧容器>你好呀</bar-container></模板>

并且您没有定义 bar-container 组件,您可以使用 CSS 选择 bar-container,这将是每个 bar 组件.但使用 <div class="bar-container"> 也同样简单.

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.

解决方案

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.

这篇关于Vue:通过 CSS 选择组件最简洁的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Vue:通过 CSS 选择组件最简洁的方法是什么?

基础教程推荐