【vue3】06. 跟着官网学习vue3
每日鸡汤:星光不问赶路人,时光不负有心人
目录
前言
一、class绑定
1.支持对象、数组、字符串
二、style绑定
1. 直接绑定object类型的字段
2. 在scss中使用js变量
总结
前言
本篇文章整理【class与style绑定】
语法没难度,依旧是整理一些常用的场景,和一些知识的扩展。
一、class绑定
1.支持对象、数组、字符串
这个没什么难度,等我遇到值得总结的会补充进来,先忽略。
二、style绑定
1. 直接绑定object类型的字段
如果我们在写一个简单组件的时候,style的变量很少,比如只有宽、高,我们一般这样写就可以了:
<template>
<div :style="{width: '100px', height: '100px'}">hello</div>
</template>
但是如果,我们有很多个需要绑定的值,比如fontSize、color、backgroundColor等,这样写就一长串,很麻烦,看起来也很乱:
<template>
<div :style="{width: '100px',
height: '100px', fontSize: '20px', color: 'red',
backgroundColor: 'blue'}">hello</div>
</template>
所以我们可以直接绑定一个object对象在模版中,这个对象的具体值在js中设置
<template>
<div :style="myStyle">hello</div>
</template>
<script setup>
const myStyle = ref({
height: '100px',
fontSize: '20px',
color: 'red',
backgroundColor: 'blue'
})
<script>
这样看起来爽多了,这种绑定好多个style的场景,一般出现在组件中,比如一个button组件,我们可以在props中传入各种样式。
既然都说到这里了,那就在延伸一个问题!
2. 在scss中使用js变量
前置知识,关于scss,可以参考我的这篇文章
【系统学习css】scss和sass以及 less的关系_我有一棵树的博客-CSDN博客每日鸡汤,每一个想要学习的念头都是未来的你向自己求救首先我们在package.json中安装的依赖都是关于sass的,但是在style标签中使用的时候一般是用<style lang="scss>这是为什么呢,我们来看一下sass和scss的关系。参考链接sass和scss其实是一样的css预处理语言,scss是sass 3引入的新语法,所以就是说scss隶属于sass,scss语法完全兼容了css3, 并且继承了sass的强大功能。区别是sass 是有严格缩进风格的,不https://blog.csdn.net/qq_17335549/article/details/116618563这个问题是。我在写一个button组件的时候遇到的,很简单,但是对于当时的我一点也不想不到。
假设,我们有一个自定义组件button可以自定义color,我们把传入的color分别应用在button和p标签上,这样我们写了两遍关于color的style的绑定:
<!-- myButton.vue -->
<template>
<button class="my-button" :style="{color: color}">{{text}}</button>
<p :style="{color: color}">这是一段文字</p>
</template>
<script setup>
import { defineProps } from 'vue'
const props = defineProps({
text: {
type: String,
default: '点击一下'
},
color: {
type: String,
default: 'red'
}
})
</script>
<style lang="scss">
.my-button {
border: 1px solid;
}
</style>
我现在想,是不是可以优化一些呢?把style绑定写一次,当然可以:
<!-- myButton.vue -->
<template>
<div class="outer-box" :style="{'--text-color': color}">
<button class="my-button">{{text}}</button>
<p class="text">这是一段文字</p>
</div>
</template>
<script setup>
import { defineProps } from 'vue'
const props = defineProps({
text: {
type: String,
default: '点击一下'
},
color: {
type: String,
default: 'red'
}
})
</script>
<style lang="scss">
.outer-box {
border: 1px solid;
.my-button, .text {
color: var(--text-color); // 使用css变量
}
}
</style>
解释一下, 我们给外层容器outer-box设置了一个css的变量--text-color,这样outer-box和他的子元素都可以使用这个变量设置css属性了。(注意仅在它子元素和自身有效,这就是作用域的问题,这也就是为什么,我们会在button外面加一个div包一下)
css变量,规则集所指定的选择器定义了自定义属性的可见作用域。
关于css变量,我会在【我不熟悉的css】系列文章中总结,欢迎围观。
总结
至此,我们学习了使用style和class的绑定,很简单,加油,努力学习才是我们唯一的出路。