关于vue 常用指令,以及动态添加样式,单选效果,多选效果样式实现。
一、常用的vue指令?
1.v-text和v-html
v-text直接把文字绑定到html。
<div v-text="text"></div>
v-html不但可以把文字绑定到html上,还可以在html中添加元素。
<div v-html="html"></div>
<script>
export default {
data(){
return{
html:"<span>使用v-html的渲染</span>"
}
}
}
</script>
2.v-if和v-show
它们两个都可是实现元素的显示或不显示,不同的是v-if是销毁或创建元素,v-show是通过控制元素的css display值来实现显示隐藏。
3.v-once
只根据数据渲染一次,往后不管数据怎么变化都不会跟新页面。
4.v-for
v-for用来迭代渲染,达到循环的操作目的,可以迭代数组,数组对象,对象或是数字。
5.v-on
v-on是用来绑定事件的监听器,也可以用@代替。它有很多修饰符
- .stop 阻止事件冒泡
- .prevert 拦截默认事件
- .captrue 添加事件侦听器时使用 capture 模式
- .self 只当事件是从侦听器绑定的元素本身触发时才触发回调
- .once 只触发一次
- .natice 监听组件根元素的原生事件
- .left 点击鼠标左键是触发
- .right 点击鼠标右键时触发
- .middle 点击鼠标中键时触发
- .passive 不拦截默认事件
6.v-model
它可以实现在表单控件或者组件上创建双向绑定。
7.v-bind
用来绑定属性,属性后面的等号指向数据,它可以简写为冒号“:”。
二、动态添加样式
【对象】
html :style="{ color: activeColor, fontSize: fontSize + ‘px’ }"
html :style="{color:(index==0?conFontColor:’#000’)}"
【数组】
html :style="[baseStyles, overridingStyles]"
html :style="[{color:(index==0?conFontColor:’#000’)},{fontSize:‘20px’}]"
【三目运算符】
html :style="{color:(index0?conFontColor:’#000’)}"
html :style="[{color:(index0?conFontColor:’#000’)},{fontSize:‘20px’}]"
三.单选效果
思路:当点击的索引值 == v-for循环的索引值时,给你那个li添加选中样式
代码如下(示例):
html代码
<ul class="box">
<li v-for="(item,index) in list" :class="{checked:index==n}" @click="changeList(index)">{{item}}</li>
</ul>
js代码
var app = new Vue({
el : ".box",
data : {
list: ["上海","北京","广州","重庆","西安"],
n : 0
},
methods :{
changeList(index){
this.n= index;//this指向app
}
}
})
css代码
body{margin:0;}
ul{
padding:0; list-style:none;
margin:150px 150px;
}
li{
width:80px; height:50px;
display:inline-block;
border-radius:8px; border:1px #000 solid;
text-align:center; line-height:50px;
cursor:pointer;
transition:all 0.3s linear;
margin-left:5px;
}
li:hover{
background-color:#0CF; color:#fff;
border:1px #fff solid;
}
li.checked{
background-color:#0CF; color:#fff;
border:1px #fff solid;
}
四、多选效果
主要的区别在于数据中有没已有标注是选中状态还是未选中状态
<ul>
<li v-for='(item,index) in list' :class="item.checked?'checked':''" @click='check(index)'> {{item.name}}
</li>
</ul>
let vm = new Vue({
el: '#app',
data: {
list: [{
checked: false,
name: '上海',
id: 0
},
{
checked: false,
name: '北京',
id: 1
},
{
checked: false,
name: '广州',
id: 2
},
{
checked: false,
name: '重庆',
id: 3
},
{
checked: false,
name: '西安',
id: 4
},
]
},
methods:{
check(i){
this.list[i].checked=!this.list[i].checked
}
}
})
body {
margin: 0;
}
.box {
margin: 150px 150px;
}
ul {
padding: 0;
list-style: none;
}
li {
width: 50px;
height: 30px;
display: inline-block;
text-align: center;
line-height: 30px;
cursor: pointer;
margin-left: 5px;
}
li:before {
display: inline-block;
width: 10px;
height: 10px;
line-height: 10px;
content: "";
border: 1px #000 solid;
margin-right: 2px;
transition: all 0.3s linear;
}
li.checked:before {
background-color: #0CF;
border: 1px #fff solid;
}
li.checked {
color: #0CF;
}