Java登陆第三十六天——VUE3引入CSS

在一个.Vue文件中,通常包括以下三部分。

  1. <template>

  2. <style>

  3. <script>

.vue中部分 传统部分 描述
<template> HTML 代替传统的.html文件
<style> CSS 代替传统的.js文件
<script> JS 代替传统的.css文件

声明内部的CSS

在.Vue文件中,style标签声明CSS。

HelloWorld.vue

<script setup>

</script>

<template>
  <p>我是helloWorld.vue</p>
</template>

<style scoped>
p{
  color: green;
}
</style>

这种方式声明的CSS仅作用于本.Vue文件中。

引入外部的CSS

项目结构如下:(在src下新建style文件夹,内部存储外部CSS)
image

test.css内

p{
    color: red;
}

script标签引入外部的CSS:

App.vue

<script setup>
  import './style/test.css'
</script>

<template>
  <p>hello world</p>
</template>

<style scoped>
</style>

效果展示
image

style标签引入外部的CSS:

修改test.css文件,把字体颜色变成绿色。

App.vue

<script setup>

</script>

<template>
  <p>hello world</p>
</template>

<style scoped>
@import "./style/test.css";
</style>

效果展示
image

全局CSS

main.js作为Vue的默认入口,在这里引入的CSS就是全局CSS。

App.vue

<script setup>
</script>

<template>
  <p>hello world</p>
</template>

<style scoped>
</style>

main.js

import { createApp } from 'vue'
import './style/test.css'
import App from './App.vue'

createApp(App).mount('#app')

效果展示
image

CSS覆盖问题

无论引入的是CSS还是组件,都会被内部CSS覆盖

HelloWorld.vue

<script setup>
</script>

<template>
  <p>我是helloWorld.vue</p>
</template>

<style scoped>
p{
  color: green;
}
</style>

App.vue

<script setup>
//引入外部的HelloWorld.vue组件,作为Hello标签使用
import Hello from './components/HelloWorld.vue'
</script>

<template>
<!--
Vue2中,template标签内只允许拥有一个子标签,通常是使用一个div把内容包裹起来
Vue3中则无该限制
  -->
  <p>hello world</p>
  <Hello></Hello>
</template>

<style scoped>
p{
  color: red;
}
</style>

效果展示
image

全局CSS也会被内部CSS覆盖

App.vue

<script setup>
</script>

<template>
  <p>hello world</p>
</template>

<style scoped>
p{
  color: red;
}
</style>

test.css

p{
    color: green;
}

main.js

import { createApp } from 'vue'
import './style/test.css'
import App from './App.vue'

createApp(App).mount('#app')

效果展示
image

posted @ 2024-04-02 19:55  rowbed  阅读(119)  评论(0编辑  收藏  举报