前端框架vue.js系列(3):样式语法

来源:互联网 发布:拉爆淘宝首页流量 编辑:程序博客网 时间:2024/05/16 02:18

根据以往vue的实际开发经验,需求中常常需要动态变化某些元素样式,如选中当前项时样式变为高亮。这时使用vue原生自带的方法来修改样式会更加方便。通常vue调用样式有3种语法,它们分别是:内联语法、对象语法及数组语法。


内联语法

用:style="{}"的方式按原生格式添加样式,如:style="{color:'red',fontWeight:'bold' }"

<p :style="{color:'greenyellow',fontWeight:'bold' }">内联语法</p>

对象语法

这种语法是最常用的语法,格式为:class="{样式:真假}",当为真时添加样式,当为假时移除样式。

<style type="text/css">.add_active {color: greenyellow;}.add_bigsize {font-size: 30px;}</style><!-- 添加了颜色样式,但是字体没有放大 --><p :class="{add_active:true,add_bigsize:false}">对象语法</p>
(注)对象语法中的真假可与vue对象data中的数值绑定,如<p :class="{add_active:isActive}"></p>
另外,对象语法还可以通过把样式对象设为vue对象data中的一个数值,然后在元素表达式中调用。
<style type="text/css">.add_active {color: greenyellow;}.add_bigsize {font-size: 30px;}</style><!-- 添加了颜色样式,但是字体没有放大 --><p :class="objectClass">对象语法2</p><script>var vue = new Vue({el: "#app",data: {objectClass: {add_active: true,add_bigsize: false}}});</script>
对象语法样式还可以通过vue对象的computed计算出来,如:
<style type="text/css">.add_active {color: greenyellow;}</style><!-- 添加了颜色样式,但是字体没有放大 --><p :class="objectComputed">对象语法3</p><script>var vue = new Vue({el: "#app",data: {//对象语法isActive: true},computed: {objectComputed: function() {return {add_active: this.isActive && this.isActive == true //优先级低于data设值,即上一个例子}}}});</script>

数组语法

直接填入数组,数组项为vue对象的data数值,该值内容为某样式名称,默认为true。

<style type="text/css">.add_active {color: greenyellow;}.add_bigsize {font-size: 30px;}</style><p :class="[arrActive,arrBigSize]">数组语法</p><script>var vue = new Vue({el: "#app",data: {arrActive: "add_active",arrBigSize: "add_bigsize",}});</script>
若需要在数组语法中判断真假,可以使用三元表达式,如:
<style type="text/css">.add_active {color: greenyellow;}.add_bigsize {font-size: 30px;}</style><p :class="[arrActiveBo ? arrActive : '', arrBigSize]">数组语法2</p><script>var vue = new Vue({el: "#app",data: {arrActiveBo: true,arrActive: "add_active",arrBigSize: "add_bigsize",}});</script>
数组语法还可以在数组中把项设置为对象,设置方法与对象语法相同。
<p :class="[{add_active:arrActiveBo},arrBigSize]">数组语法3</p>


若设置元素为自定义组件,即可以在template按原生的方式增加样式,也可以在新组件元素上按对象语法和数组语法添加样式。如
<style type="text/css">.add_active {color: greenyellow;}.add_bigsize {font-size: 30px;}</style><my-component :class="{add_active: isActive }"></my-component><script>Vue.component('my-component', {template: '<p class="add_bigsize">组件语法</p>'})var vue = new Vue({el: "#app",data: {isActive: true,}});</script>