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
相关产品推荐
相关产品推荐

