Vue 计算属性、方法、侦听
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="./vue.v2.6.10.dev.js"></script>
</head>
<body>
<div id="app">
{{fullName}}
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
firstName: 'Muzico',
lastName: 'Liang',
},
//计算属性
computed: {
fullName: function() {
return this.firstName + " " + this.lastName
}
}
})
</script>
</body>
</html>
计算属性:内置缓存。
fullName,依赖 firstName 和 lastName,在该两个值没有改变的情况下,只会继续使用上一次的计算。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="./vue.v2.6.10.dev.js"></script>
</head>
<body>
<div id="app">
{{fullName()}}
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
firstName: 'Muzico',
lastName: 'Liang',
},
methods: {
fullName: function() {
return this.firstName + this.lastName;
}
}
})
</script>
</body>
</html>
用方法也能实现,但是方法没有缓存,就算 firstName 和 lastName 没有改变的情况下,也会重新计算。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="./vue.v2.6.10.dev.js"></script>
</head>
<body>
<div id="app">
{{fullName}}
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
firstName: 'Muzico',
lastName: 'Liang',
fullName: 'Muzico Liang',
},
watch: {
firstName: function() {
this.fullName = this.firstName + " " + this.lastName
},
lastName: function() {
this.fullName = this.firstName + " " + this.lastName
},
}
})
</script>
</body>
</html>
通过侦听 也可以实现,但是计算属性无疑是最好的选择。