vue class 与 style 绑定

Zoella Lv3

绑定一个返回对象的计算属性

1
2
3
4
5
6
7
const isActive = ref(true);
const error = ref(null);

const classObject = computed(() => ({
active: isActive.value && !error.value,
'text-danger': error.value && error.value.type === 'fatal'
}));
1
<div :class="classObject"></div>

子组件继承父组件传入的class

有一个根元素的组件

子组件的根元素,在渲染时会添加父组件的 class。

有多个根元素的组件

子组件中 :class='$attrs.class' 的根元素,在渲染时会添加父组件的 class。

1
2
3
<!-- 子组件 MyComponent.vue -->
<p :class="$attrs.class">one root element</p>
<span>another root element</span>
1
2
<!-- 父组件 -->
<MyComponent class="fatherClass"/>

渲染后结果:

1
2
<p class="fatherClass">one root element</p>
<span>another root element</span>

內联样式

绑定对象

1
2
3
4
const styleObject = reactive({
color: "red",
fontSize: "13px"
});
1
<div :style="styleObject"></div>

绑定对象数组

1
<div :style="[baseStyle, overriddingStyle]"></div>
1
2
3
4
5
6
7
8
const baseStyle = reactive({
color: "red",
...
});
const overriddingStyle = reactive({
color: "black",
...
});
  • Title: vue class 与 style 绑定
  • Author: Zoella
  • Created at : 2023-11-28 19:03:13
  • Updated at : 2023-12-26 11:21:11
  • Link: https://zoella-w.github.io/2023/11/28/6-vue class与style绑定/
  • License: This work is licensed under CC BY-NC-SA 4.0.