v-bind 对于样式控制的增强 - 操作style
语法 :style="样式对象"
适用场景: 某个具体属性的动态设置
<div class="box" :style="{ CSS属性名1: CSS属性值, CSS属性名2: CSS属性值}"></div>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<header>
<h1>记事本</h1>
<!-- 输入框: 绑定回车事件 -->
<input @keyup.enter="add" placeholder="请输入任务" v-model="todoname">
<button @click="add">添加任务</button>
</header>
<!-- 列表区域 -->
<section>
<ul>
<li v-for="(item,index) in list" :key="item.id">
<div>
<span>{{ index + 1 }}.</span><label>{{ item.name }}</label>
<button @click="del(item.id)"> X </button>
</div>
</li>
</ul>
</section>
<!-- 统计和清空 -> 如果没有任务了,底部隐藏掉 -> v-show-->
<footer v-show="list.length > 0">
<!-- 统计 -->
<span>合计: <strong>{{ list.length }}</strong></span>
<!-- 清空 -->
<button @click="clear">清空任务</button>
</footer>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<script>
const app = new Vue({
el: "#app",
// 响应式数据 -> 数据变化了,视图自动更新
data: {
todoname:'',
list: [
{ id: 1, name: '昨天吃鸡' },
{ id: 2, name: '今天王者' },
{ id: 3, name: '明天摆烂' },
]
},
methods: {
del(id){
// filter :保留所有不等于id的项
this.list = this.list.filter(item => item.id !==id)
},
add(){
//判断是否为空,trim()可以移除字符串两侧的空白字符或其他预定义字符
if (this.todoname.trim() === ''){
alert("请输入任务内容")
return
}
//往数组的最前面加
this.list.unshift({
id: +new Date(), // +new Date():当前时间时间戳
name:this.todoname
})
this.todoname=''
},
clear(){
this.list=[]
}
}
})
</script>
</body>
</html>
案例: 进度条
项目分析:
1. 两个盒子,外层是底色,内层是进度条
2. 动态绑定进度条宽度样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.progress {
width: 400px;
height: 25px;
border-radius: 15px;
background-color: #272425;
border: 3px solid #272425;
box-sizing: border-box;
margin-bottom: 30px;
}
.inner{
width: 50%;
height: 20px;
border-radius: 10px;
text-align: right;
position: relative;
background-color: #409eff;
background-size: 20px 20px;
box-sizing: border-box;
transition: all 1s;
}
</style>
</head>
<body>
<div id="app">
<!-- 外层盒子底色 (黑色) -->
<div class="progress">
<!-- 内层盒子 -进度(蓝色) -->
<div class="inner" :style="{ width: percent + '%'}">
<span>{{ percent }}%</span>
</div>
</div>
<button @click="percent = 25">设置25%</button>
<button @click="percent = 50">设置50%</button>
<button @click="percent = 75">设置75%</button>
<button @click="percent = 100">设置100%</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
percent:0
}
})
</script>
</body>
</html>