状态驱动CSS
<p><strong>写法1:行内中绑定对象</strong></p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;div :class=&quot;{ 'class1': flag, 'class2': flag }&quot;&gt;Andy&lt;/div&gt;
&lt;button @click=&quot;changeStyle&quot;&gt;change&lt;/button&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, computed } from 'vue'
let flag = ref(false)
function changeStyle() {
flag.value = !flag.value
}
&lt;/script&gt;
&lt;style&gt;
.class1 {
color: red;
}
.class2 {
font-size: 20px;
}
&lt;/style&gt;</code></pre>
<hr />
<p><strong>写法2:将行内对象放在下边</strong></p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;div :class=&quot;obj&quot;&gt;Andy&lt;/div&gt;
&lt;button @click=&quot;changeStyle&quot;&gt;change&lt;/button&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, computed } from 'vue'
let flag = ref(false)
let obj = ref({ 'class1': flag, 'class2': flag })
function changeStyle() {
flag.value = !flag.value
}
&lt;/script&gt;
&lt;style&gt;
.class1 {
color: red;
}
.class2 {
font-size: 20px;
}
&lt;/style&gt;</code></pre>
<hr />
<p><strong>写法3:行内中绑定数组</strong></p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;div :class=&quot;['class1','class2']&quot;&gt;Andy&lt;/div&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, computed } from 'vue'
&lt;/script&gt;
&lt;style&gt;
.class1 {
color: red;
}
.class2 {
font-size: 20px;
}
&lt;/style&gt;</code></pre>
<hr />
<p><strong>写法4:</strong></p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;div :class=&quot;[flag ? 'class1 class2' : '']&quot;&gt;Andy&lt;/div&gt;
&lt;button @click=&quot;changeStyle&quot;&gt;change&lt;/button&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, computed } from 'vue'
let flag = ref(false)
function changeStyle() {
flag.value = !flag.value
}
&lt;/script&gt;
&lt;style&gt;
.class1 {
color: red;
}
.class2 {
font-size: 20px;
}
&lt;/style&gt;</code></pre>
<hr />
<p><strong>写法5:</strong></p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;div&gt;Andy&lt;/div&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, computed } from 'vue'
let obj = ref({
color: 'red'
})
&lt;/script&gt;
&lt;style&gt;
div {
color: v-bind(&quot;obj.color&quot;)
}
&lt;/style&gt;</code></pre>
<hr />
<p><strong>写法6:动态修改style</strong></p>
<pre><code class="language-javascript">&lt;template&gt;
&lt;div :style=&quot;andyStyle&quot;&gt;Andy&lt;/div&gt;
&lt;button @click=&quot;changeStyle&quot;&gt;change&lt;/button&gt;
&lt;/template&gt;
&lt;script setup&gt;
import { ref, computed } from 'vue'
let andyStyle = ref({
width: '100px',
height: '100px',
background: 'red',
})
function changeStyle() {
andyStyle.value = {
width: '100px',
height: '100px',
background: 'yellow',
}
}
&lt;/script&gt;</code></pre>