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>

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

相关推荐
梦想平凡9 分钟前
百游棋牌源代码开发搭建教程(十):隔离部署、备份恢复与双端验收
java·前端·javascript·数据库·源代码管理
kyriewen4 小时前
我花3天抓了一个幽灵bug,凶手藏在第4层
前端·javascript·程序员
mONESY5 小时前
LangGraph.js 从零上手:把 Agent 工作流从一条线变成一张网
javascript
默_笙5 小时前
⚓ AI 的"官方答题卡":withStructuredOutput 与结构化输出的终局之战
前端·javascript
我家猫叫佩奇7 小时前
🦭 厌倦了千篇一律的线性图标?Naive Icons 正式开源
前端·javascript·css
梦诺9 小时前
vue3 keepAlive+记录滚动条
前端·javascript·vue.js
天若有情67310 小时前
开源轻量双语工具|一键批量查询 NPM 包历史下载量,支持按作者批量统计
javascript·npm·github pages·开源工具·netlify·前端开源·npm克隆量
福兮说12 小时前
纯前端把图片压缩到指定体积:canvas.toBlob 配合二分查找
前端·javascript·canvas·图片处理
志尊宝12 小时前
Vue3 零基础每日笔记(018):按键与鼠标修饰符——回车搜索、Ctrl+S 保存这样写
javascript·vue.js·笔记
可乐鸡翅yeah_13 小时前
HLS流媒体首屏起播慢深度优化,从分片、索引、播放器全链路调优
开发语言·javascript·ecmascript·m3u8·m3u8在线