vue style标签scoped属性作用

本文探讨 Vue.js 中 scoped 属性如何限制组件样式仅在当前组件生效,以及不使用 scoped 时全局样式的影响。同时,介绍了组件懒加载的方式及其与 scoped 样式的关系。示例展示了非懒加载和懒加载情况下,组件样式应用的差异。
摘要由CSDN通过智能技术生成

vue style标签scoped属性作用

  • 限制加了scoped属性的样式仅在当前组件生效
  • 如果不加scoped标签样式则作用在全局,
  • 加了scoped标签的组件样式仍可受到作用在全局的样式的影响
  • 组件中可使用ref代替id去使用,样式最好不要通过id去写

组件懒加载和组件未使用scoped属性的影响

懒加载方式导入组件:
  1. 父组件:
<template>
  <div id="app">

    <button @click="show2 =!show2">按钮</button>
    <CPOne />
    <CPTwo v-if="show2" />
  </div>
</template>

<script>

import CPOne from './components/CPOne.vue'
// import CPTwo from './components/CPTwo.vue' // 非懒加载方式导入

export default {
  name: 'App',
  components: {
    CPOne,
    // CPTwo // 非懒加载方式导入
    CPTwo: () => import('./components/CPTwo.vue') // 懒加载方式引用组件
  },
  data() {
    return {
      show2: false
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

  1. 子组件1:
<template>
  <div id="CPOne" class="CPOne">
    <h4 class="h4">我是组件一,我会受影响吗?</h4>
  </div>
</template>

<script>
export default {

}
</script>

<style scoped>
</style>

  1. 子组件2:
<template>
  <div id="CPTwo" class="CPTwo">我是组件2</div>
</template>

<script>
export default {

}
</script>

<style >
.h4 {
  background: green;
}
</style>

  1. 实现效果:
    组件懒加载,未加载时候的样式
    懒加载,组件2加载之后效果
非懒加载方式导入组件:
  1. 组件1:(仅组件1代码不同!)
<template>
  <div id="app">

    <button @click="show2 =!show2">按钮</button>
    <CPOne />
    <CPTwo v-if="show2" />
  </div>
</template>

<script>

import CPOne from './components/CPOne.vue'
import CPTwo from './components/CPTwo.vue' // 非懒加载方式导入

export default {
  name: 'App',
  components: {
    CPOne,
    CPTwo // 非懒加载方式导入
    // CPTwo: () => import('./components/CPTwo.vue') // 懒加载方式引用组件
  },
  data() {
    return {
      show2: false
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

  1. 实现效果:
    非懒加载的效果
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值