<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="./vue.js"></script>
<!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
<div id="app">{{fullName}} {{age}}</div>
<script type="text/javascript">
var vm = new Vue({
el: "#app",
data: {
firstName: "Tom",
lastName: "Cat",
age: 18
/*fullName: "Tom Cat" //然而这样会有冗余变量,可以用computed来解决*/
},
//计算属性
computed: {
fullName: function() {
console.log("计算了一次")
return this.firstName + " " + this.lastName //别忘了return
}
}
})
</script>
</body>
</html>
可以看到,刷新页面输出“计算了一次”,改变firstName又输出“计算了一次”,而改变age不会再输出“计算了一次”。如果fullName依赖的firstName、lastName没有改变,则不会再重新计算,因为已经把它们缓存了起来
当然还可以通过methods的方式来实现,但是只要页面重新渲染,fullName就会重新执行一次,它没缓存。所以,同样的功能,用computed会比methods更好
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="./vue.js"></script>
<!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
//注意fullName()的()
<div id="app">{{fullName()}} {{age}}</div>
<script type="text/javascript">
var vm = new Vue({
el: "#app",
data: {
firstName: "Tom",
lastName: "Cat",
age: 18
/*fullName: "Tom Cat" //然而这样会有冗余变量,可以用computed来解决*/
},
/*//计算属性
computed: {
fullName: function() {
console.log("计算了一次")
return this.firstName + " " + this.lastName //别忘了return
}
}*/
//当然还可以通过methods的方法来实现:
methods: {
fullName: function() {
console.log("计算了一次")
return this.firstName + " " + this.lastName
}
}
})
</script>
</body>
</html>
也可以用监听(watch)的方式:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="./vue.js"></script>
<!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
<div id="app">{{fullName}} {{age}}</div>
<script type="text/javascript">
var vm = new Vue({
el: "#app",
data: {
firstName: "Tom",
lastName: "Cat",
age: 18,
fullName: "Tom Cat" //然而这样会有冗余变量,可以用computed来解决
},
/*//计算属性
computed: {
fullName: function() {
console.log("计算了一次")
return this.firstName + " " + this.lastName //别忘了return
}
}*/
/*//当然还可以通过methods的方法来实现:
methods: {
fullName: function() {
console.log("计算了一次")
return this.firstName + " " + this.lastName
}
}*/
//还可以用监听的方式:
watch: {
firstName: function() {
console.log("计算了一次");
this.fullName = this.firstName + " " + this.lastName
},
lastName: function() {
console.log("计算了一次");
this.fullName = this.firstName + " " + this.lastName
}
}
})
</script>
</body>
</html>
(看得出来,只有在监听的发生改变才会执行)
总结:如果一个功能可以通过method、computed、watch来实现,首选computed。因为它和watch一样会缓存,而且写的代码比watch少,更优于不缓存的method