Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue scoped

作者:颓废的爱情   发布日期:2025-08-12   浏览:73

<template>
  <div class="parent">
    <p class="text">This is scoped CSS example</p>
    <child-component></child-component>
  </div>
</template>

<script>
export default {
  name: 'ParentComponent',
  components: {
    ChildComponent: {
      template: '<div class="child"><p class="text">I am a child component</p></div>'
    }
  }
}
</script>

<style scoped>
.parent {
  background-color: lightblue;
}

.text {
  color: red;
}

.child .text {
  color: green;
}
</style>

解释说明:

  1. <template> 部分:

    • 包含一个 div 元素,类名为 parent,里面有一个段落元素 p,类名为 text
    • 还包含了一个子组件 ChildComponent
  2. <script> 部分:

    • 定义了一个名为 ParentComponent 的 Vue 组件。
    • components 中定义了一个子组件 ChildComponent,它包含一个 div 元素,类名为 child,里面有一个段落元素 p,类名为 text
  3. <style scoped> 部分:

    • scoped 属性使得样式仅应用于当前组件的模板中。
    • .parent 类设置了背景颜色为浅蓝色。
    • .text 类设置了文本颜色为红色,但只在父组件中生效。
    • .child .text 类设置了子组件中的文本颜色为绿色,即使子组件也有 .text 类,但由于 scoped 的作用,这里的样式不会影响全局或其他组件。

通过这种方式,你可以确保样式的局部性,避免样式污染其他组件。

上一篇:vue2 provide

下一篇:vue3 sass

大家都在看

vue.config.js configu

node.js vue

vue 图表组件

vue3watch监听多个变量

vue查看版本

vue3 reactive对象重新赋值

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站