【问题标题】:Inline CSS styling behavior in VueJsVueJs 中的内联 CSS 样式行为
【发布时间】:2021-03-11 19:52:17
【问题描述】:

我的 HTML 中有一个 ,它可以将

上的背景颜色设置为内联样式。我尝试了两种设置样式的方法,但我不理解一种特定的行为:如果我输入蓝色,两个段落都会变成蓝色。但是,如果我执行退格,第 2 段将保持蓝色,直到输入字段为空或具有另一种有效颜色(例如:从黄绿色退格到黄色),这对我来说很奇怪。另一方面,第 1 段具有预期的行为:如果输入不是有效颜色,则它是无样式的。

我想这与 Vue 将“样式对象”转换为实际 css 样式的方式有关。它是如何工作的? (以防万一:我对 Vue.js 完全陌生)

HTML:

<section id="assignment">
  <input type="text" v-model="bgc" />
  <p :style="bgcInlineStyle">Paragraph 1</p>
  <p :style="{backgroundColor: bgc}">Paragraph 2</p>
</section>

JS:

const app = Vue.createApp({
  data() {
    return {
      bgc: "",
    };
  },
  computed: {
    bgcInlineStyle() {
      return `background-color:${this.bgc};`;
    },
  },
});

app.mount("#assignment");

【问题讨论】:

    标签: css vue.js inline


    【解决方案1】:

    这是因为计算属性是根据它们的反应性依赖来缓存的

    参考:Computed Property and Caching

    【讨论】:

      【解决方案2】:

      在第 1 段中,您将字符串值绑定到样式属性。

      在第 2 段中,您将对象值绑定到样式属性。

      对于字符串值,浏览器会解析样式属性并立即更新渲染。如果添加了无效的属性或无效的属性值,CSS 将忽略它。

      对于对象值,Vue 将使用对象键值对动态更新样式属性。如果遇到无效值,它将忽略该属性并避免通过 JavaScript 更新它。这就是背景颜色保持蓝色的原因。

      Vue 使用 JavaScript 处理样式对象,例如:

      document.querySelector("p").style.backgroundColor = "blue";
      document.querySelector("p").style.backgroundColor = "blu"; // this will be ignored, it will not 'reset' the value to a blank state
      

      【讨论】:

        猜你喜欢
        • 2012-02-11
        • 1970-01-01
        • 1970-01-01
        • 2018-07-01
        • 2013-06-26
        • 2017-12-19
        • 2016-09-01
        • 2011-04-28
        • 2014-09-25
        相关资源
        最近更新 更多