scoped样式修饰符的使用

在这里插入图片描述

在Vue.js中,scoped 是一个用于样式的修饰符,它用于限定样式的作用范围,使得样式只在当前组件的作用域内生效,而不会影响到父组件或子组件的样式。这个特性通常用于解决 CSS 样式污染的问题,确保样式只会影响到当前组件的 DOM 元素。

Scoped 样式的基本用法

在Vue组件的<style>标签中使用scoped属性,可以将样式限定在当前组件的作用域内。示例代码如下:

<template>
  <div class="app">
    <h1>Vue Scoped Styles</h1>
    <button @click="toggleColor">Toggle Color</button>
    <p class="global-style">大家好,我是IT小辉同学!!!</p>
    <p class="scoped-style">希望与大家一起学习,成长!!!</p>
  </div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      isRed: false,
    };
  },
  methods: {
      
      
    toggleColor() {
      
      
      this.isRed = !this.isRed;
    },
  },
};
</script>

<style scoped>
/* Scoped styles */
p {
      
      
  color: blue;
}

/* Global styles */
.global-style {
      
      
  font-weight: bold;
}

/* Conditional styling */
.scoped-style {
      
      
  color: red;
}
</style>

在上面的示例中,<style scoped> 标签中的样式只会应用于当前组件的<p>元素,而不会影响到全局样式或其他组件中的元素。

示例1:条件样式绑定

<template>
  <div>
    <p :class="{ 'red-text': isRed }">热爱,就要坚持,勇往直前!!!</p>
    <button @click="toggleColor">相信梦想!!!</button>
  </div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      isRed: false,
    };
  },
  methods: {
      
      
    toggleColor() {
      
      
      this.isRed = !this.isRed;
    },
  },
};
</script>

<style scoped>
.red-text {
      
      
  color: red;
}
</style>

上面的示例中,<p> 元素的样式会根据 isRed 变量的值而改变。这个样式只会影响到当前组件的<p>元素,不会影响到其他组件。

示例2:组件嵌套

<template>
  <div>
    <h2>把我的故事讲给你听。。。。。。</h2>
    <child-component></child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
      
      
  components: {
      
      
    ChildComponent,
  },
};
</script>

<style scoped>
h2 {
      
      
  color: blue;
}
</style>

在这个示例中,父组件的样式只会影响到父组件内的元素,而不会影响到子组件 ChildComponent 内的元素。

示例3:深度选择器

在Vue中,你还可以使用 ::v-deep/deep/ 伪类来影响子组件中的样式。这是一个例子:

<template>
  <div>
    <h2>希望我们都能够勇敢一些。。。。。。</h2>
    <child-component></child-component>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
      
      
  components: {
      
      
    ChildComponent,
  },
};
</script>

<style scoped>
::v-deep h2 {
      
      
  color: blue;
}
</style>

这会影响到子组件 ChildComponent 中的 <h2> 元素的样式。

上面几个示例都非常详细的帮助大家了解了一下怎么使用scoped,以及其作用。scoped 样式是Vue.js中用于隔离组件样式的一种非常有用的特性,可以确保组件样式不会影响全局样式或其他组件,从而提高了代码的可维护性和可重用性。希望大家可以经常使用,同时,深入了解!!!

猜你喜欢

转载自blog.csdn.net/weixin_53742691/article/details/132679350