Vue的计算属性,方法和侦听器。
计算属性
-
代码:
-
控制台输入
vm.age = 22
,fullName
不会执行,控制台输入vm.firstName = "xxx"
,fullName
会执行
方法
- 效果
- 代码
- 控制台输入
vm.age = 22
,fullName
会执行,控制台输入vm.firstName = "xxx"
,fullName
会执行
侦听器
-
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="http://vuejs.org/js/vue.js"></script>
<title>计算属性,方法和侦听器</title>
</head>
<body>
<div id="app">
{{fullName}}
{{age}}
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
firstName: "Kyrie",
lastName: "Irving",
fullName: "Kyrie Irving",
age: 18
},
watch: {
firstName: function () {
console.log("计算了一次")
this.fullName = this.firstName + " " + this.lastName
},
lastName: function () {
console.log("计算了一次")
this.fullName = this.firstName + " " + this.lastName
}
}
})
</script>
</body>
</html> -
控制台输入
vm.age = 22
,fullName
不会执行,控制台输入vm.firstName = "xxx"
,fullName
会执行,但是代码简洁度不高,所以能用计算属性就优先使用计算属性。
计算属性的setter和getter
- 效果
- 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算属性的setter和getter</title>
<script src="http://vuejs.org/js/vue.js"></script>
</head>
<body>
<div id="app">
{{fullName}}
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
firstName: "Kyrie",
lastName: "Irving",
},
computed: {
fullName: {
get: function () {
return this.firstName + " " + this.lastName
},
set: function (value) {
var array = value.split(" ")
this.firstName = array[0]
this.lastName = array[array.length - 1]
}
}
}
//控制台输入vm.fullName = "Leborn James",名字会随之更新
})
</script>
</body>
</html>