vue中scss使用js的变量

一、前言

在项目开发中,很多时候会涉及到scss样式变量,正常定义方式 $primary-color: rgb(188, 0, 194);;使用时直接使用即可:color: $primary-color。但是,如果,这些变量是在js中定义的怎么办

二、实现
  1. 动态绑定::style="{'--str-length': strLength}"
  2. scss 中使用 v-bind(strLength) => strLength 是js变量
html 复制代码
<template>
    <div class="typing-demo-wrapper" :style="{'--str-length': strLength}">
      <div class="typing-demo">{{ text }}</div>
    </div>
</template>

<script lang="ts" setup>
const text = ref("你好;欢迎来到自定义布局页面。");
const strLength = text.value.length; // 计算字符串长度;
</script>

<style lang="scss" scoped>
.typing-demo-wrapper {
    height: 200px;  // 父元素的元素可按实际情况处理
    overflow: auto;

    /* 实现从左到右打字效果 */
    @keyframes typing {
      from {
        width: 0
      }
    }
    /* 实现鼠标闪烁效果 */
    @keyframes blink {
      50% {
        border-color: transparent
      }
    } 
    .typing-demo {
      font-family: monospace; /* 使用等宽字体,保证每个字的宽度一致 */      
      // width: 30ch; /* 设置宽度为字符串长度 */

      // 根据字符串长度设置宽度
      width: calc(var(--str-length) * 2ch); // 使用动态绑定的css变量,计算宽度
      // width: calc(v-bind(strLength) * 2ch); // 直接使用v-bind绑定js变量

      /* typing 3s 表示3秒内打完这15个字  blink  .5s表示0.5秒闪烁一下光标*/
      animation: typing 3s steps(v-bind(strLength)), blink .5s step-end infinite alternate;
      white-space: nowrap;
      overflow: hidden;
      /* 鼠标光标用右边的边框代替 */
      border-right: 2px solid red;
      font-size: 2em; 
    }
  }
</style>

文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出!

相关推荐
DevUp12 小时前
标着 JavaScript 的 Wiki 与知识库:既不是 CMS 也不是 SSG(番外三)
javascript·node.js·cms
kyriewen13 小时前
我上手了 Vite+ 1.0:Node 不用自己装,lint 却翻车了
前端·javascript·程序员
鹏多多14 小时前
前端是如何死去的?| 完整时间线
前端·javascript·程序员
古夕14 小时前
iframe 授权失败时露出 60000 JSON 的复盘
前端·javascript
程序员Sunday14 小时前
ES Module 和 CommonJS 有什么区别?循环依赖时会发生什么?
前端·javascript·面试
有味道的男人15 小时前
搜好货平台关键词商品搜索接口:分页容错与商品数据轻量化提取方案
服务器·前端·javascript
雪雪爱冲浪18 小时前
JavaScript 网络爬虫教程(2026)
开发语言·javascript·爬虫
软件技术NINI18 小时前
化妆品html+css+js 7页
javascript·css·html
要吃这碗饭18 小时前
JavaScript 网络爬虫教程(2026)
开发语言·javascript·爬虫
lexiangqicheng18 小时前
自定义表单跨端共用机制-PC设计APP渲染
java·前端·javascript