Vue 基础知识学习
禁用生产提示:Vue.config.production = false
1. 事件(methods)
- 点击事件
@click = "helloworld"
或者v-on:click="helloworld"
- 传递参数
@click="hellworld(666)"
- 传递参数丢失event,
@click="helloworld(666,$event)"
- 阻止默认事件:@click.prevent=“helloworld"
- 阻止事件冒泡(2种方式):
- e.stopPropagation()
- @click.stop=“helloworld”
- 事件只触发一次 @click.once=“helloworld”
- 事件捕获:@click.capture
- 只有e.target是当前元素才调用 @click.self=“helloworld”
键盘事件
键盘码:e.key.code 键盘名:e.key
2.数据绑定
v-bind 单向绑定
v-model 双向绑定
列表渲染
数据集
const vm = new Vue({
el : '#root',
data: {
persons: [
{ id: '2201',name:"李华",age:22 },
{ id: '2202',name:"张三" ,age:23},
{ id: '2203',name:"小明" ,age:20},
],
car:{
name:'奥迪A8',
price:'70万',
color:'黑色'
},
},
methods: {
add(){
const p = {id:"2204",name:"thinker",age:40}
this.persons.unshift(p)
}
}
})
数组渲染
<h2>学生列表1</h2>
<ul>
<li v-for="p in persons">{{p.id}}-{{p.name}}-{{p.age}}</li>
</ul>
对象渲染
使用key和不使用key的效果
key是列表遍历的唯一标识,不指定key会默认使用遍历的索引值index为key.在使用key是应考虑使用数据集中的唯一标识,如数据id,若使用index,对数组进行头插,会发现key是变化的,导致插入的数据达不到理想效果.
初始态,此时采用数组的index作为key,对数组进行头插,新插的数据就会index =0 ,vue的虚拟dom对比算法会将新的虚拟dom和旧的虚拟dom 进行diff,会尽可能让真实dom复用:
如图可见,inputtext被复用了
虚拟dom对比算法图:
解决策略,使用key时,使用数据集的唯一标识,而非index
<li v-for="(a,b) in persons" :key="a.id">{{a}}--------{{b}} <input type="text"/></li>
列表过滤(使用监视器watch)
data : {
keywords :"",
persons: [
{id:"111",name:"周杰伦",age:49,sex:"男"},
{id:"222",name:"杨紫琼",age:49,sex:"女"},
{id:"333",name:"周润发",age:49,sex:"男"},
{id:"555",name:"巩俐",age:49,sex:"女"},
],
fillPerson:[],
},
watch:{
keywords :{
immediate:true,
handler(val){
this.fillPerson = this.persons.filter((p) =>{
return p.name.indexOf(val) !==-1;
})
}
}