Vue 响应式渲染 - Vue2 Class和style
Vue 渐进式JavaScript 框架 基于Vue2的学习笔记 - Vue响应式渲染 - Vue2 Class和style
目录
Vue2 Class和style
动态切换class-对象
添加新类
如何解决方案
动态切换class-数组
增加类方式
动态切换style-对象
在data中设置变量
动态添加底层不支持
增加元素
动态添加样式
总结
Vue2 Class和style
引用Vue2版本在多个class之间切换。
动态切换class-对象
title1、title2、title3都是style中设置的类,
在vue的data中定义一个变量,
来对div进行类的批量赋值。
示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.title1 {
color:red;
}
.title2 {
font-weight: bold;
}
.title3 {
background: #ccc;
}
</style>
<script src="../lib/vue.js"></script>
</head>
<body>
<div id="box">
<div :class="classobj">动态切换class-1-对象</div>
</div>
<script>
let vm = new Vue({
el:'#box',
data:{
classobj: {
title1:true,
title2:true,
title3:false,
}
}
})
</script>
</body>
</html>
添加新类
在控制台通过定义的vm添加新的类。
示例如下:
后期(临时)添加的类,不会拦截,无法侦听到。
示例如下:
如何解决方案
Vue2 Vue.set(目标对象,属性,true)
Vue3 支持动态增加属性的拦截。
动态切换class-数组
使用数组方式动态切换div的class,示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.title1 {
color: red;
}
.title2 {
font-weight: bold;
}
.title3 {
background: #ccc;
}
.title4 {
border: 2px solid #000;
}
</style>
<script src="../lib/vue.js"></script>
</head>
<body>
<div id="box">
<div :class="classobj">动态切换class-1-对象</div>
<div :class="classarr">动态切换class-2-数组</div>
</div>
<script>
var vm = new Vue({
el: '#box',
data: {
classobj: {
title1: true,
title2: true,
title3: false,
},
classarr: ["title1", "title4"]
}
})
</script>
</body>
</html>
增加类方式
这时想新增一个类,如果操作,示例如下:
动态切换style-对象
通过vue动态绑定div的行内样式,就可以通过对象方式动态切换style。
示例如下:
<div :style="styleobj">动态切换style-1-对象</div>
在data中设置变量
设置styleobj变量,使用对象方式,在其中设置属性时需注意使用驼峰语法,
示例如下:
styleobj: {
backgroundColor:'blue'
}
动态添加底层不支持
Vue2 解决方案
使用Vue.set(vm.styleobj, "fontSize", "30px")
示例如下:
增加元素
在页面增加div。示例如下:
<div :style="stylearr">动态切换style-2-数组</div>
在data中设置变量,如下:
动态添加样式
vm.stylearr.push({fontSize:"30px"})
总结
Vue 渐进式JavaScript 框架 基于Vue2的学习笔记 - Vue响应式渲染 - Vue2 Class和style