跟着网上学Vue之样式绑定

class属性

从某鸟教程里面发现一段代码,容易搞混
在style中添加的样式:

.active {
	width: 100px;
	height: 100px;
	background: green;
}
.text-danger {
	background: red;
}

在body中添加的代码:

<div id="app">
  <div class="static"
     v-bind:class="{ active: isActive, 'text-danger': hasError }">
  </div>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    isActive: true,
	hasError: true
  }
})
</script>

结果图:
在这里插入图片描述

  • 一开始很纠结为什么是红色覆盖绿色,然后试了很多方法,突然想起来是“就近原则”,然后我就试着把style的样式顺序换一下,结果成功了。(新手要注意了

此外,在通过vue设置class的时候,还可以通过对象传值
某鸟教程说的:

<div v-bind:class="classObject"></div>
new Vue({
  el: '#app',
  data: {
    classObject: {
      active: true,
      'text-danger': true
    }
  }
})

数组设置class

//body中
<div v-bind:class="[activeClass, errorClass]"></div>
//script中
new Vue({
  el: '#app',
  data: {
    activeClass: 'active',
    errorClass: 'text-danger'
  }
})

三元式设置class

//body中
<div v-bind:class="[errorClass ,isActive ? activeClass : '']"></div>
//script中
new Vue({
  el: '#app',
  data: {
    isActive: true,
	activeClass: 'active',
    errorClass: 'text-danger'
  }
})

设置style

  1. 普通设置style
//body内
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">教程</div>

//script内
new Vue({
  el: '#app',
  data: {
    activeColor: 'green',
	fontSize: 30
  }
})
  1. 单个样式对象设置style
//body内
 <div v-bind:style="styleObject">教程</div>
//script内
new Vue({
  el: '#app',
  data: {
    styleObject: {
      color: 'green',
      fontSize: '30px'
    }
  }
})
  1. 多个样式对象设置style
//body内
 <div v-bind:style="[baseStyles, overridingStyles]">教程</div>
 //script内
 new Vue({
  el: '#app',
  data: {
    baseStyles: {
      color: 'green',
      fontSize: '30px'
    },
	overridingStyles: {
      'font-weight': 'bold'
    }
  }
})

注意:当 v-bind:style 使用需要特定前缀的 CSS 属性时,如 transform ,Vue.js 会自动侦测并添加相应的前缀。

发布了73 篇原创文章 · 获赞 0 · 访问量 1223

猜你喜欢

转载自blog.csdn.net/qq_38605145/article/details/105264110