Vue3 样式绑定
Vue.js class
class 与 style 是 HTML 元素的属性,用于设置元素的样式,我们可以用 v-bind 来设置样式属性。
v-bind 在处理 class 和 style 时, 表达式除了可以使用字符串之外,还可以是对象或数组。
v-bind:class 可以简写为 :class。
.active {
width: 100px;
height: 100px;
background: green;
}
</style>
</head>
<body>
<div id="app">
<div :class="{ 'active': isActive }"></div>
</div>
<script>
const app = {
data() {
return {
isActive: true
}
}
}
练习:输入姓名 年龄(不是数字就有提示) 爱好(下拉列表)
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<style>
p{
width:80%;
margin:0 auto;
}
input,
select{
display: inline-block;
width: 50%;
height:25px;
}
select{
height:40px;
}
button{
width:100px;
background: rgb(41,135,243);
color:white;
}
.err_content li{
color:red;
}
</style>
</head>
<body>
<form id='my_form' @submit="checkForm">
<div class='err_content' v-if="errMsg.length">
<b>错误提示:</b>
<ul>
<li v-for="err in errMsg">{{err}}</li>
</ul>
</div>
<p>
<label for="name">姓名:</label>
<input id="name" name="name" type="text" v-model="name" placeholder="这里填姓名">
</p>
<br>
<p>
<label for="age">年龄:</label>
<input id="age" name="age" type="text" v-model="age" placeholder="这里填年龄" min='0' max='100'>
</p>
<p>
<label for='likes'>爱好:</label>
<select name="likes" id="likes" v-model="likes">
<option value="">选择一个爱好</option>
<option value="1">书</option>
<option value="2">代码</option>
</select>
</p>
<br>
<p>
<button type='submit'>提交</button>
</p>
<script type="text/javascript">
new Vue({
el:'#HUA',
data:function(){
return{
errMsg:[],
name:null,
age:null,
likes:null
}
},
methods:{
checkForm(e){
this.errMsg=[]
if(!this.name){
this.errMsg.push('用户姓名不为空')
}
if(!this.age){
this.errMsg.push('年龄输入错误')
}
if(!this.likes){
this.errMsg.push('爱好不能为空')
}
if(!this.errMsg.length){
return true
}
e.preventDefault()
}
}
});
</script>