Vue.js中class与style的增强绑定实现方法

您所在的位置:网站首页 js常用的绑定点击事件的方法 Vue.js中class与style的增强绑定实现方法

Vue.js中class与style的增强绑定实现方法

#Vue.js中class与style的增强绑定实现方法| 来源: 网络整理| 查看: 265

Vue.js中class与style的增强绑定实现方法

在web前端应用中,操作元素的class列表的内联样式style是数据绑定style是数据绑定的一个常见需求,因为它们都是attribute,所有可以用v-bind处理它们,但若样式复杂,则需要书写长串的样式代码,这样一来,字符串拼接就比较麻烦。因此,在将v-bind用于class和style时,Vue.js做了专门的增强,表达式结果的类型除了字符串之外,还可以是对象或数组。

 

一、v-bind绑定class属性

若想使用类样式(即以类名定义元素的样式,类样式一般以"."号开头命令),可以通过v-bind指令绑定class属性实现:

(1)绑定class样式,字符串写法

适用于:样式的类名不确定,需要动态指定

{{name}} const vm = new Vue({ el: '#root', data: { name: "class和style增强绑定", moon: "normal" }, methods: { doChange() { var arr = ["happy", "sad", "normal"]; indexof = Math.floor(Math.random() * 3); this.moon = arr[indexof]; } } });

css样式:

.happy { border: 4px solid red; background-color: rgba(255, 255, 0, 0.644); background: linear-gradient(30deg, yellow, pink, orange); } .sad { border: 4px dashed rgb(2, 197, 2); background-color: gray; } .normal { background-color: skyblue; }

执行结果:

(2)绑定class样式,数组写法

适用于:要绑定的样式个数不确定,名字也不确定

{{name}} const vm = new Vue({ el: '#root', data: { name: "class和style增强绑定", classarr: ["text_1", "text_2", "text_3"], }, methods: { } });

css样式:

.text_1 { background-color: yellowgreen; } .text_2 { font-size: 30px; text-shadow: 2px 2px 10px red; } .text_3 { border-radius: 20px; }

执行结果:

(3)绑定class样式,对象写法

适用于:要绑定的样式个数和名字也确定,需要动态显示

{{name}} const vm = new Vue({ el: '#root', data: { name: "class和style增强绑定", classobj: { text_1: false, text_2: true, text_3: false, }, }, methods: { } });

css样式:

.text_1 { background-color: yellowgreen; } .text_2 { font-size: 30px; text-shadow: 2px 2px 10px red; } .text_3 { border-radius: 20px; }

执行结果:

 

二、v-bind绑定内联样式style

通过内联(style)绑定给DOM元素示例:

(1)绑定style样式---对象形式 绑定style样式----对象形式 {{name}} const vm = new Vue({ el: '#root', data: { name: "class和style增强绑定", styleobj: { width: "300px", height: "100px", border: "1px solid black", fontSize: "40px", backgroundColor: "blue" }, }, methods: { } });

执行结果:

(2)绑定style样式---数组写法 绑定style样式----数组写法 {{name}} const vm = new Vue({ el: '#root', data: { name: "class和style增强绑定", stylearr: [ {width: "300px"}, {height: "100px"}, {border: "1px solid black"}, {backgroundColor:"red"}, {fontSize:"20px"} ], }, methods: { } });

执行结果:

关于Vue.js中class与style的增强绑定的文章就介绍至此,更多相关Vue.js class与style绑定内容请搜索编程宝库以前的文章,希望以后支持编程宝库!

下一节:AntDesignVuetable组件如何自定义分页器JS 编程技术

 Ant Design Vue table组件自定义分页器由 Ant Design of Vue 提供的Table表格组件自身是带有pagination分页功能的,用于获取到 ...



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3