簡體   English   中英

Vue.js的動態樣式

[英]Dynamic style with Vue.js

我想添加和刪除樣式pointer-events:none; Vue.js動態添加屬性:

 new Vue({ el: '#el', data: { toggled: false }, methods: { toggle: function () { this.toggled = !this.toggled; }, } }) 
 <script src="https://cdn.jsdelivr.net/npm/vue"></script> <div id="el"> <!-- The style disables all mouse events in the div --> <div style="pointer-events:none;"> ... </div> <button v-on:click="toggle">Toggle click</button> </div> 

我應該怎么做?

謝謝您的幫助。

 new Vue({ el: '#el', data: { toggled: false }, methods: { toggle: function () { this.toggled = !this.toggled; }, } }) 
 <script src="https://cdn.jsdelivr.net/npm/vue"></script> <div id="el"> <!-- The style disables all mouse events in the div --> <div :style="{ 'pointer-events': toggled ? 'none' : null }"> ... </div> <button v-on:click="toggle">Toggle click</button> </div> 

您的<button>#el之外,導致Vue無法對其進行解析。

要動態更改HTML組件上的樣式,可以基於數據值將類分配給或刪除給定組件,例如:

<template>
   <div @click="toggleData=!toggleData">Click to toggle</div>
   <div :class="[toggleData ? 'classA' : 'classB']"></div>
</template>

<script>
export default {
  data() {
    return {
      toggleData: false,
    };
  },
</script>

<style>
.classA{
  pointer-events:none;
}
.classB{
    pointer-events:auto;
}
</style>

您可以使用返回對象的計算屬性,其中key表示屬性,value表示css屬性值。 這是使用計算屬性的示例-

<div id="el">
  <!-- The style disables all mouse events in the div -->
  <div v-bind:style="dynamicStyleObject">
  ...
  </div>
  <button v-on:click="toggle">Toggle click</button>
</div>


computed:{
    dynamicStyleObject:function(){
       // Conditionally return object in the following format -
       return {
          'pointer-events' : 'none',
          'some-other-property' : 'some-value'
       };
    }
}

使用計算屬性非常方便,因為只要組件的數據發生更改,dynamicStyleObject就會自動發生相應的更改。

我想你正在尋找這樣的東西

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM