项目前导 学习笔记
一、视图更新
1.1、触发视图更新
Vue 对一些方法进行了包装和变异,以后数组通过这些方法进行数组更新,会触发视图的更新。(就是在页面看到数据的变化)
- 直接赋值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue 保持状态</title>
</head>
<body>
<div id="app">
<div v-for="value in books">
<label for="value">{{value}}</label>
</div><br>
<button @click="updatelist">视图更新</button>
</div>
</body>
</html>
<script src="./vue.js"></script>
<script>
new Vue({
el: "#app",
data: {
books: ['Python','JAVA','C++','PHP']
},
methods: {
updatelist:function(){
// 直接赋值
this.books = ['三国演义','水浒传','红楼梦','西游记','金瓶梅']
}
}
})
</script>
push()
:在末尾添加元素的方法。
methods:{
updatelist:function(){
// 在末尾添加元素
this.books.push("GO")
}
}
unshift(item)
:在数组的开头位置添加一个元素。
methods:{
updatelist:function(){
// 在数组的开头位置添加一个元素
this.books.unshift("GO")
}
}
pop()
:删除数组最后一个元素。
methods:{
updatelist:function(){
// 删除数组最后一个元素
this.books.pop()
}
}
shift()
:删除数组的第一个元素。
methods:{
updatelist:function(){
// 删除数组第一个元素
this.books.shift()
}
}
splice(index,howmany,item1,...,itemX)
:向数组中添加或者删除或者替换元素。
methods:{
updatelist:function(){
// 向 books 第 0 个位置添加元素
this.books.splice(0,0,"金瓶梅")
// 下标从0开始,删除2个元素
this.books.splice(0,2)
// 下标从0开始,替换2个元素
this.books.splice(0,2,'金瓶梅','骆驼祥子')
// 从 books 第 1 个位置开始修改 2 个元素
this.books.splice(1,2,"金瓶梅")
}
}
sort(function)
:排序。
methods:{
updatelist:function(){
this.books.sort(function(x,y){
<!-- 取两个随机数排序 -->
a = Math.random();
b = Math.random();
return a-b;
});
}
}
reverse()
:将数组元素进行反转。
methods:{
updatelist:function(){
// 在数组的开头位置添加一个元素
this.books.reverse()
}
}
1.2、视图更新注意事项
- 直接修改数组中的某个值是不会出发视图更新的。
- 比如:
// 想要修改 books 数组的第 0 个值
this.books[0] = 'Python';
- 这种情况应该改成用
splice
或者是用Vue.set
方法来实现:
// 修改数组中第 0 个值
Vue.set(this.books,0,'Python');
- 如果动态的给对象添加属性,也不会触发视图更新。只能通过
Vue.set
来添加。比如:
<div v-for="(value, key) in person">
<label>{{key}}: {{value}}</label>
</div>
<button @click="updatelist">添加值</button>
data: {
person: {
name: '老A'
}
},
methods:{
updatelist:function(){
Vue.set(this.person, 'age', 18)
}
}
二、事件
2.1、事件绑定
事件绑定就是在 HTML 元素中,通过 v-on
绑定事件的。事件代码可以直接放到 v-on
后面,也可以写成一个函数。
<div id="app">
<p>{{count}}</p>
<button v-on:click="count+=1">加</button>
<button v-on:click="subtract(2)">减2</button>
</div>
<script>
let vm = new Vue({
el: "#app",
data: {
count: 0
},
methods: {
// subtract: function(value=1) { this.count -= value; }
// 可简写为如下:
// 不传参时减 1
subtract(value=1){
this.count -= value;
}
}
});
</script>
2.2、event 参数
如果在事件处理函数中,想要获取原生的 DOM
事件,那么在 html 代码中,调用的时候,可以传递一个 $event
参数。
<button v-on:click="subtract(2, $event)">减2</button>
...
<script>
...
methods: {
subtract: function(value, event){
this.count -= value;
// 打印 event 参数
console.log(event);
}
}
...
</script>
扫描二维码关注公众号,回复:
10869708 查看本文章