computed
Example
<template>
<div class="box">
<input type="text" v-model="keyCode" placeholder="筛选" />
<ul>
<li v-for="(item, index) in filterCode" :key="index">{
{ item }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
keyCode: "",
list: ["apple", "huawei", "sony", "oppo", "vivo"],
};
},
computed: {
filterCode() {
var arr = [];
for (let i in this.list) {
if (this.list[i].indexOf(this.keyCode) != -1) {
arr.push(this.list[i]);
}
}
return arr;
},
},
};
</script>
watch
Example
<template>
<div class="box">
<input type="text" v-model="firstName" placeholder="姓" />
<input type="text" v-model="lastName" placeholder="名" />
{
{ fullName }}
</div>
</template>
<script>
export default {
data() {
return {
firstName: "",
lastName: "",
fullName: "",
};
},
watch: {
firstName(value) {
this.fullName = `${
value}${
this.lastName}`;
},
lastName(value) {
this.fullName = `${
this.firstName}${
value}`;
},
},
};
</script>
computed
- Rely on data cache, only execute when the data changes
- Asynchronous is not supported. It is invalid when there are asynchronous operations in the computed, and it is impossible to monitor data changes.
- Variables do not need to be defined in the data function
watch
- Support asynchronous operation of data changes
- Receive two parameters, the first parameter is the latest value; the second parameter is the value before the input
- The monitoring data must be the data in the props declared in the data or passed by the parent component
- Incur a large performance overhead