You need to enable JavaScript to run this app. Vue项目报Cannot set style of string variable错误如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Vue项目报Cannot set style of string variable错误如何解决?

解决方案

错误原因

你代码中的mainTitle是纯字符串类型,并非DOM元素实例,不存在style属性,直接对其赋值style.fontSize会触发类型错误。

正确实现方式

在Vue中需要将文本内容和动态样式分开处理,通过模板的动态样式绑定能力实现需求,具体修改如下:

1. 拆分逻辑修改JS方法

// 返回处理后的标题文本
getTitleText(){
  const getTitle = this.titleText;
  const countGetTitle = getTitle.split(" ").length;
  if(countGetTitle > 4){
    return getTitle.replace(/(\S+\s*){1,5}/, "$&\n");
  }
  return getTitle;
},
// 返回对应的字体大小
getTitleFontSize(){
  const countGetTitle = this.titleText.split(" ").length;
  return countGetTitle > 4 ? "30px" : "40px";
}

2. 模板中绑定内容和样式

在页面模板中对标题标签同时绑定内容和动态style即可:

<template>
  <!-- 其他页面代码 -->
  <div :style="{fontSize: getTitleFontSize()}">{{ getTitleText() }}</div>
  <!-- 其他页面代码 -->
</template>

可选简化方案

如果不想定义两个方法,也可以直接返回包含文本和样式的配置对象:

getTitleConfig(){
  const getTitle = this.titleText;
  const countGetTitle = getTitle.split(" ").length;
  if(countGetTitle > 4){
    return {
      text: getTitle.replace(/(\S+\s*){1,5}/, "$&\n"),
      fontSize: "30px"
    }
  }
  return {
    text: getTitle,
    fontSize: "40px"
  }
}

模板使用方式:

<div :style="{fontSize: getTitleConfig().fontSize}">{{ getTitleConfig().text }}</div>

内容的提问来源于stack exchange,提问作者sandeep Chhetri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 12:24:04