当前位置: 移动技术网 > IT编程>脚本编程>vue.js > Vue 样式绑定的实现方法

Vue 样式绑定的实现方法

2019年03月16日  | 移动技术网IT编程  | 我要评论

七魔传人,webosquickinstall,wirelessmon专业版

学习 vue 的时候觉得样式绑定很简单,但是使用的时候总是容易搞晕自己。因为 :class 和 :style 里的数组语法和对象语法和 data 里绑定的值是不太一样的。这篇文章就简单对 vue 绑定做个总结。

操作元素的class列表和内联样式是数据绑定的一个常见需求,因为它们都是属性,所以可用v-bind处理,通过表达式计算出字符串结果即可。不过字符串拼接麻烦且易错。因此,在将v-bind用于class和style时,vue做了专门增强,表达式结果类型除了字符串之外,还可是对象或数组。

  • class绑定
  • style绑定

绑定class

对象语法

data 里的属性是负责 toggle 是否要这个 class,也就是一般定义 boolean 类型的值。

<div :class="{ active: isactive, 'text-danger': haserror }"></div>

这里用 isactive 和 haserror 定义是否需要 active 和 text-danger 类。

data: {
 isactive: true,
 haserror: false
}

渲染为

<div class="active"></div>

数组语法

data 里负责定义 css 类名。

<div :class="[activeclass, errorclass]"></div>

这里定义了 activeclass 和 errorclass 的 css 类名是 active 和 text-danger。

data: {
 activeclass: 'active',
 errorclass: 'text-danger'
}

渲染为

<div class="active text-danger"></div>

混合写法

可以用混合的形式来绑定 class,即数组语法里写对象语法。所以 data 里的数据主要用于:

  1. 是否需要某个 class
  2. 定义 "class" 里面的类名
<div :class="[{ active: isactive }, errorclass]"></div>

这里定义了 errorclass 的 css 类名为 text-danger,并用 isactive 定义是否需要 active 类。

data: {
 errorclass: 'text-danger',
 isactive: true
}

渲染为

<div class="active text-danger"></div>

绑定style

对象语法

data 里的属性是定义 style 里的值。与 class 不一样,class 是定义是否要这个 class的。

<div :style="{ color: activecolor, fontsize: fontsize + 'px' }"></div>

这里定义了 style 里的 color 和 font-size 的值。

data: {
 activecolor: 'red',
 fontsize: 30
}

渲染为

<div style="color: red; font-size: 30px"></div>

数组语法

可以绑定多个样式对象到 style 上

<div :style="[basestyles, overridingstyles]"></div>

这里在 data 里用 styleobject 定义了 color 和 font-size,再用 overridingstyles 定义了 background 和 margin。然后在组件里用数组进行混合绑定。

data: {
 styleobject: {
  color: 'red',
  fontsize: '13px'
 },
 overridingstyles: {
  background: 'green',
  margin: '13px'
 }
}

渲染为

<div style="color: red; font-size: 13px; background: green; margin: 13px;"></div>

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网