Vue3动态样式

Vue3动态样式

一. Vue3动态样式

我们准备一个简单的Vue3项目,并写两个页面:Home

<template>
  <h1>Home</h1>
  <div>
    {
    
    {
    
     number }}
    <button @click="add">1</button>
  </div>
</template>

<script setup lang="ts">
import {
    
     ref, reactive, toRef } from "vue";

const state = reactive({
    
    
  count: 1,
  color: "black",
});
const colorRef = toRef(state, "color");
const add = () => {
    
    
  state.count++;
  colorRef.value = state.count % 2 == 0 ? "blue" : "red";
};
</script>

<style scoped>
h1 {
    
    
  color: v-bind(colorRef);
}
</style>

About页面:

<template>
    <h1>About</h1>
</template>

效果如下:
在这里插入图片描述

记得添加路由。添加好之后,我们点击加1按钮,看看会发生什么?
在这里插入图片描述

首先来看下我们做的事情:

  1. 我们定义了几个响应式数据,其中有个colorRef,它会根据count变量是奇数还是偶数来改变颜色。
  2. 我们使用了v-bind()来讲这个响应式数据绑定在了h1标签上。

上面就包含了本文想说的几个点:

  1. 我们可以使用v-bind,方便的去将CSS样式和响应式数据进行绑定,响应式数据的值可以作为CSS样式来使用。
  2. 如果在style标签中,添加 scoped属性,代表当前这个样式的作用域仅仅在当前组件当中。我们可以看到对应的样式名称带着一定的前缀。
    在这里插入图片描述

上述在style样式里面添加v-bind的写法还有第二种,就是直接将表达式赋值上去:

h1{
    
    
    color: v-bind('state.count % 2 == 0 ? "blue" : "red"');
}

但是这种方式需要注意,一定要在表达式的最外层增加引号。即你传入的整体一定是一个字符串。只不过它的内容体是一个三元表达式。

猜你喜欢

转载自blog.csdn.net/Zong_0915/article/details/128918481