计算属性(通过其他的值算出新值):避免数据冗余
特点:内置缓存,当计算属性依赖的变量没有发生改变时,这个计算属性就不会再执行,就会一直用上一次计算的结果,这样就能提高性能。
上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>6.计算属性,方法和侦听器</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">{{fullName}}{{position}}</div>
<script>
var vm = new Vue({
el: '#app',
data: {
state: 'China',
province: 'Guangdong',
position: 'south'
// fullName: 'China Guangdong' //数据冗余
},
// 计算属性
computed: {
fullName: function () {
console.log('计算了一次');
return this.state + " " + this.province
}
},
})
</script>
</body>
</html>
方法:没有缓存机制,页面只要重新渲染,方法就会重新执行一次。
上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>6.计算属性,方法和侦听器</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">{{fullName()}}{{position}}</div>
<script>
var vm = new Vue({
el: '#app',
data: {
state: 'China',
province: 'Guangdong',
position: 'south'
// fullName: 'China Guangdong' //数据冗余
},
methods: {
fullName: function () {
console.log('方法');
return this.state + " " + this.province
}
},
})
</script>
</body>
</html>
侦听器 :有缓存,性能还可以,就是复杂了。
上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>6.计算属性,方法和侦听器</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">{{fullName}}{{position}}</div>
<script>
var vm = new Vue({
el: '#app',
data: {
state: 'China',
province: 'Guangdong',
fullName: 'China Guangdong', //数据冗余
position: 'south',
},
watch: {
// 侦听state的改变,state不变化,侦听器state就不会执行
state: function () {
console.log('侦听');
this.fullName = this.state + " " + this.province
},
// 侦听province的改变,province不变化,侦听器province就不会执行
province: function () {
console.log('侦听');
this.fullName = this.state + " " + this.province
}
},
})
</script>
</body>
</html>
网友评论