【问题标题】:Is it possible to bind the inline style with vue.js?是否可以将内联样式与 vue.js 绑定?
【发布时间】:2019-06-28 00:20:33
【问题描述】:

我很好奇,可以在Vue.js中绑定内联样式吗?我对类绑定很熟悉,但是如果有时出于某种原因你想内联绑定样式声明,是否可以像绑定类一样绑定它?

例如:

<template>
  <div>
      <h1 :style="{('background:red') : condition}"> Text </h1>
      <button @click='condition = true'>Click me</button>
  </div>
</template>

<script> 
export default {
  data(){
   return {
   condition:false 
          }
         }
   }
</script>

在上面的示例中,我想在条件为真时更改元素的背景。

【问题讨论】:

    标签: javascript html css vue.js


    【解决方案1】:

    是的,有可能请通过docs

    注意:为了更好的调试,请使用computed,methods而不是inline

    <template>
      <div>
        <h1 :style="styleObject"> Text </h1>
        <button @click='toggleCondition'>Click me</button>
      </div>
    </template>
    
    <script>
    
    export default {
      data() {
        return {
          condition: false,
        };
      },
      computed: {
        styleObject() {
          return this.condition ? { background: 'red' } : {};
        },
      },
      methods: {
        toggleCondition() {
          this.condition = !this.condition;
        },
      },
    };
    
    </script>
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"&gt;&lt;/script&gt;

    【讨论】:

    • Tnx,我对 vue 还是有点陌生​​,所以没有阅读所有文档,需要快速阅读。你和托马斯对我说得很清楚!
    【解决方案2】:

    当然可以,如下所述:https://vuejs.org/v2/guide/class-and-style.html

    <template>
      <div>
          <h1 v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"> Text </h1>
          <button @click='condition = true'>Click me</button>
      </div>
    </template>
    
    <script> 
    export default {
      data(){
       return {
       condition:false,
       activeColor: 'white',
       fontSize: 12
              }
             }
       }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2011-12-05
      • 2017-02-06
      • 2011-01-28
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      相关资源
      最近更新 更多