作者:黑糖老姜茶 | 来源:互联网 | 2024-11-05 18:45
篇首语:本文由编程笔记#小编为大家整理,主要介绍了Vue 开发实战基础篇 # 9:合理应用计算属性和侦听器相关的知识,希望对你有一定的参考价值。 说明 【Vue 开发实战】学习笔记。 计算属性 com
篇首语:本文由编程笔记#小编为大家整理,主要介绍了Vue 开发实战基础篇 # 9:合理应用计算属性和侦听器相关的知识,希望对你有一定的参考价值。
说明
【Vue 开发实战】学习笔记。
计算属性 computed
- 减少模板中计算逻辑
- 数据缓存.
- 依赖固定的数据类型(响应式数据)
<template>
<div>
<p>Reversed message1: " reversedMessage1 "p>
<p>Reversed message2: " reversedMessage2() "p>
<p> now p>
<button &#64;click&#61;"() &#61;> $forceUpdate()">forceUpdatebutton>
<br />
<input v-model&#61;"message" />
div>
template>
<script>
export default
data()
return
message: "hello vue"
;
,
computed:
reversedMessage1: function()
console.log("执行reversedMessage1");
return this.message
.split("")
.reverse()
.join("");
,
now: function()
return Date.now();
,
methods:
reversedMessage2: function()
console.log("执行reversedMessage2");
return this.message
.split("")
.reverse()
.join("");
;
script>
侦听器 watch
- 更加灵活、通用
- watch 中可以执行任何逻辑&#xff0c;如函数节流,&#xff0c;Ajax异步获取数据&#xff0c;甚至操作DOM
<template>
<div>
$data
<br />
<button &#64;click&#61;"() &#61;> (a &#43;&#61; 1)">a&#43;1button>
div>
template>
<script>
export default
data: function()
return
a: 1,
b: c: 2, d: 3 ,
e:
f:
g: 4
,
h: []
;
,
watch:
a: function(val, oldVal)
this.b.c &#43;&#61; 1;
console.log("new: %s, old: %s", val, oldVal);
,
"b.c": function(val, oldVal)
this.b.d &#43;&#61; 1;
console.log("new: %s, old: %s", val, oldVal);
,
"b.d": function(val, oldVal)
this.e.f.g &#43;&#61; 1;
console.log("new: %s, old: %s", val, oldVal);
,
e:
handler: function(val, oldVal)
this.h.push("&#x1f604;");
console.log("new: %s, old: %s", val, oldVal);
,
deep: true
,
h(val, oldVal)
console.log("new: %s, old: %s", val, oldVal);
;
script>
computed VS watch
- computed 能做的&#xff0c;watch都能做&#xff0c;反之则不行
- 能用 computed 的尽量用 computed
Computed1.vue
<template>
<div>
fullName
<div>firstName: <input v-model&#61;"firstName" />div>
<div>lastName: <input v-model&#61;"lastName" />div>
div>
template>
<script>
export default
data: function()
return
firstName: "Foo",
lastName: "Bar"
;
,
computed:
fullName: function()
return this.firstName &#43; " " &#43; this.lastName;
,
watch:
fullName: function(val, oldVal)
console.log("new: %s, old: %s", val, oldVal);
;
script>
Watch1.vue
<template>
<div>
fullName
<div>firstName: <input v-model&#61;"firstName" />div>
<div>lastName: <input v-model&#61;"lastName" />div>
div>
template>
<script>
export default
data: function()
return
firstName: "Foo",
lastName: "Bar",
fullName: "Foo Bar"
;
,
watch:
firstName: function(val)
this.fullName &#61; val &#43; " " &#43; this.lastName;
,
lastName: function(val)
this.fullName &#61; this.firstName &#43; " " &#43; val;
;
script>