动态样式

Siona

动态样式

动态设置背景颜色

在 Vue 3 中,你可以使用动态绑定的方式来设置元素的背景颜色。 首先,确保你的样式中定义了 CSS 变量,然后通过 Vue 的数据绑定将其应用到元素上。

以下是一个示例:


<template>
    <div
        :style="{ '--custom-bg-color': dynamicBackgroundColor , '--custom-position-left': position.x + 'px', '--custom-position-top': position.y + 'px'}">
        <!-- Your content goes here -->
    </div>
</template>

<script setup lang="ts">
    import {ref} from 'vue';

    const dynamicBackgroundColor = ref('red'); // 初始颜色,你可以根据需求修改

    const props = defineProps<{
        lf: any,
        model: any,
        show: any,
        position: any,
    }>();

    // 在某个事件或条件下修改颜色
    const changeBackgroundColor = () => {
        dynamicBackgroundColor.value = 'blue'; // 修改为想要的颜色
    };
</script>

<style scoped lang="scss">
    div {
        background-color: var(--custom-bg-color);
        display: block;
        top: var(--custom-position-top);
        left: var(--custom-position-left);
        /* 其他样式 */
    }
</style>

这里,dynamicBackgroundColor 是一个 ref,你可以在组件中修改它的值, 然后通过动态绑定 :style 将其应用到元素的 --custom-bg-color CSS 变量上。 这样,当 dynamicBackgroundColor 改变时,背景颜色也会相应地改变。

position.x, position.y 是从父组件传过来的位置,注意在 <template> 中用时,可能会需要拼接 'px'

变量形式动态设置样式


<template>
    <div class="node-next">
          <span
              :style="isNodeNextVisible"
              @mousedown.stop="handleNext">
              <span class="next-icon"><CirclePlusFilled/></span>
          </span>
    </div>
</template>
<script setup lang="ts">
    import {CSSProperties, reactive} from "vue";

    const isNodeNextVisible = reactive<CSSProperties>({
        visibility: 'hidden'
    });

    isNodeNextVisible.visibility = (props.properties.type !== 'endNode' && hasNextNode()) ? 'visible' : 'hidden';
    /* 需要注意的点:所赋的值 必须是该属性的可以用的值 */
</script>
Last Updated 6/11/2024, 9:46:19 AM