1计算属性
# 1 计算属性是基于它们的依赖变量进行缓存的
# 2 计算属性只有在它的相关依赖变量发生改变时才会重新求值,否则不会变(函数只要页面变化,就会重新运算)
# 3 计算属性就像Python中的property,可以把方法/函数伪装成属性
# 4 计算属性,必须有返回值
案例
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><script src="https://cdn.staticfile.org/vue/2.7.0/vue.min.js"></script>
</head>
<body><div id="app"><input type="text" v-model="username"> ------ {{handles()}}<br><p>计算属性</p><input type="text" v-model="username1"> ------ {{handless}}</div><script>var vm = new Vue({el:'#app',data:{username:'',username1:'',age:''},methods:{handles(){console.log('函数打印了')var str =this.usernamereturn str=str.slice(0,1).toUpperCase() +str.slice(1).toLowerCase()}},computed:{handless(){console.log('计算属性打印了')var str =this.username1return str=str.slice(0,1).toUpperCase() +str.slice(1).toLowerCase()}}})</script>
</body>
</html>
2监听属性
# 属性如果发生变化,就会执行某个函数
写在watch中
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><script src="./js/vue.js"></script>
</head>
<body>
<div id="app"><h1>监听属性</h1><input type="text" v-model="username"> --->{{username}}
</div>
</body>
<script>var vm = new Vue({el: '#app',data: {username: '',},watch: {username(newValue, oldValue) {console.log('老值', oldValue)console.log('新值', newValue)console.log('我发生变化了')}}})
</script>
</html>