<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<h1>1.计算属性computed VS 方法</h1>
<!-- 计算属性是基于它们的响应式依赖进行缓存的。只在相关响应式依赖发生改变时它们才会重新求值。
我们为什么需要缓存?假设我们有一个性能开销比较大的计算属性 A,它需要遍历一个巨大的数组并做大量的计算。
然后我们可能有其他的计算属性依赖于 A。如果没有缓存,我们将不可避免的多次执行 A 的 getter!-->
<p>原始数据 {{message}}</p>
<p>反转后的数据 {{reversedMessage}}</p>
<p>使用方法得到的反转后的数据{{MethodreversedMessage()}}</p>
<h1>2.计算属性computed VS 监听属性watch</h1>
<p>{{fullName}}</p>
<h1>3.监听属性watch</h1>
<p>当前计数:{{ count }}</p>
<button @click="increase">+1</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data:{
message: 'Hello!',
firstName:'张',
lastName: '三',
// fullName: '张三'
count: 0,
},
methods: {
MethodreversedMessage(){
return this.message.split('').reverse().join('')
},
increase(){
this.count++;
}
},
computed: {
//计算属性的getter
reversedMessage: function (){
// `this` 指向 vm 实例
return this.message.split('').reverse().join('')
},
fullName: function (){
return this.firstName+this.lastName
}
},
watch: {
firstName: function (val) {
this.fullName = val + this.lastName
},
lastName: function (val) {
this.fullName = this.firstName + val
},
count(newValue,oldValue){
console.log('count的值发生变化,变化后的新值为:'+newValue ,'变化前的旧值为'+oldValue)
}
}
})
</script>
</body>
</html>
Vue基础使用之计算属性Computed和监听属性Watch
于 2024-04-16 16:40:31 首次发布