【问题标题】:Modifying fontSize throws an error - TypeError: "fontSize" is read-only修改 fontSize 会抛出错误 - TypeError: "fontSize" is read-only
【发布时间】:2021-07-15 08:40:27
【问题描述】:

我有一个 Vue.js 应用程序。在我的组件中,我想确保 div 内的文本适合其内容。这是我在mounted 钩子中的逻辑:

  mounted() {
    const front = this.$refs.frontContainer;
    const subject = this.$refs.subjectContainer;
    const fontSize = 1.1;
    while (front.offsetHeight < front.scrollHeight) {
      fontSize -= 0.05;
      subject.style.fontSize = fontSize + 'em';
    }
  }

模板(简体)如下:

<template>
<div class="front-data" ref="frontContainer">
  <span ref="subjectContainer" class="subject">{{ event.subject }}</span>
</div>
</template>

每当我加载我的页面时,我都会看到错误:

[Vue 警告]:挂载钩子错误:“TypeError:“fontSize”是只读的”

TypeError: "fontSize" 是只读的

为什么它不起作用?我在W3C 上发现我应该可以设置 fontSize。

【问题讨论】:

  • 您将其声明为 const... 常量,就像它们的名字所暗示的那样,不能更改。使用let
  • 我确定错误出现在subject.style.fontSize = fontSize + 'em'; 行。当然,你是对的,我错过了。

标签: javascript html vue.js


【解决方案1】:

如果要修改值,请使用 let 而不是 const

let fontSize = 1.1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 2011-09-29
    • 1970-01-01
    • 2011-04-20
    • 2021-10-19
    • 1970-01-01
    • 2013-09-16
    • 2020-11-07
    相关资源
    最近更新 更多