侦听器/监听器 watch
watch 侦听器/监听器 可以监听 data中数据的变化; watch里面的名字就是用数据的名字
可以接受两个参数 current(变化后的值),prev(变化之前的值)
watch: {
count(current, prev) {
console.log('count changed');
this.newTotal = this.price * current;
},
message(current, prev) {
console.log('message changed start');
console.log('current:', current);
console.log('prev:', prev);
console.log('message changed end');
}
}
Watch和computed的区别: computed在页面渲染的同时执行里面的业务逻辑,而且必须有一个返回值;
可以用watch实现computed的功能,但实现上会更加复杂
method、Watch和computed使用优先级:
computed 和 method都能实现的功能,建议使用computed,因为有缓存,不用渲染页面就刷新。
computed 和 watch 都能实现的功能,建议使用 computed,因为更加简洁。
Demo13.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello World</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<p> watch 侦听器/监听器 可以监听 data中数据的变化; watch里面的名字就是用数据的名字</p>
<p> 可以接受两个参数 current(变化后的值),prev(变化之前的值) </p>
<br>
<p> Watch和computed的区别: computed在页面渲染的同时执行里面的业务逻辑,而且必须有一个返回值; </p>
<p> 可以用watch实现computed的功能,但实现上会更加复杂 </p>
<br>
<p> method、Watch和computed使用优先级: </p>
<p> computed 和 method都能实现的功能,建议使用computed,因为有缓存,不用渲染页面就刷新。 </p>
<p> computed 和 watch 都能实现的功能,建议使用 computed,因为更加简洁。 </p>
<div id="app"></div>
</body>
<script>
const app = Vue.createApp({
data() {
return {
message: 'Hello world',
price: 10,
count: 2,
newTotal: 20
}
},
methods: {
getTotal() {
return this.price * (this.count);
},
getTotal2() {
return Date.now();
},
messageBtnClick() {
this.message = this.message == 'Hello world' ? 'Good Bye' : 'Hello world';
},
countBtnClick() {
this.count++;
}
},
computed: {
computeTotal() {
return this.price * (this.count);
},
computeTotal2() {
return Date.now();
}
},
watch: {
count(current, prev) {
console.log('count changed');
this.newTotal = this.price * current;
},
message(current, prev) {
console.log('message changed start');
console.log('current:', current);
console.log('prev:', prev);
console.log('message changed end');
}
},
template: `<h1>{{price * count}}</h1>
<br>
<h2>{{getTotal()}}</h2>
<h2>{{message}}</h2>
<h2>{{getTotal2()}}</h2>
<br>
<h2>{{computeTotal}}</h2> <h2>计算属性使用时用的是属性名,不需要括号()</h2>
<h2>{{message}}</h2>
<h2>{{computeTotal2}}</h2>
<br>
<h2>{{newTotal}}</h2> <h2>用watch实现computed功能</h2>
<br>
<button @click='messageBtnClick'>Message Button Click</button>
<button @click='countBtnClick'>Count Button Click</button>
`
});
const vm = app.mount("#app");
</script>
</html>