Vue3 新特性 Computed、Watch、WatchEffect 看完就会

开发 前端
WatchEffect 与Computed 类似,Computed 注重计算出来的结果,所以必须要返回值,而它注重的是过程,所以不用写返回值。

1、watchEffect

watchEffect 侦听器是一个副作用函数,不需要指定监听的某个属性,监视的回调中用到哪个属性,就会监听哪个属性,一旦运行就会立即执行。

watchEffect 与 computed 类似,computed 注重计算出来的结果,所以必须要返回值,而它注重的是过程,所以不用写返回值。

使用语法:

watchEffect(() => {
//需要监听的属性
}, WatchEffectOptions)
// WatchEffectOptions 更多的配置项

watchEffect 使用实例:

<template>
<div>
动物:
<input v-model="fish.name" />
<br />
类型
<input v-model="fish.type" />
</div>
</template>
<script lang="ts" setup>
import { reactive, watchEffect } from 'vue'
interface Animal {
name: string
type: string
}
let fish = reactive<Animal>({
name: '酸菜鱼',
type: '又酸又菜又多余',
})
watchEffect<Animal>(() => {
console.log('fish', fish.name)
console.log('fish', fish.type)
})
</script>

刷新页面,首次进入的时候,watchEffect 回调函数会自动执行。

为什么说 watchEffect 是副作用函数呢?

副作用函数就是指会产生副作用的函数,也就是说函数在执行的时候会直接或间接影响其他函数的执行。watchEffect 副作用就是 DOM 挂载或更新之前就会触发。

运行下面的实例,发现:

<template>
<div>
动物:
<input id="ipt" v-model="fish.name" />
</div>
</template>
<script lang="ts" setup>
import { reactive, watchEffect } from 'vue'
interface Animal {
name: string
type: string
}
let fish = reactive<Animal>({
name: '酸菜鱼',
type: '又酸又菜又多余',
})
watchEffect<Animal>(() => {
console.log('fish', fish.name)
const ipt: HTMLElement = document.querySelector('#ipt') as HTMLElement
console.log('ipt', ipt)
})
</script>

第一次获取到的元素是 null,执行第二次监听的时候才会获取到元素。

如何清除 watchEffect 的副作用呢?

上述的问题可以通过 flush:post 可以避免副作用,在 DOM 更新后运行副作用,确保模板引用与 DOM 保持同步,并引入正确元素。

vue3 新特性 computed、watch、watchEffect 看完就会

WatchEffectOptions 主要作用是指定调度器,何时运行副作用函数。它是一个可选参数,具体属性值有:

  • flush
  • onTrack
  • onTrigger

flush 定义组件刷新时机,它有三个值,分别表示意义如下:


pre

sync

post

更新时机

组件更新前执行

强制效果始终同步触发

组件更新后执行

onTrack 和 onTrigger 用于调试一个侦听器的行为。

清除副作用函数(onInvalidate)。

watchEffect 的第一个参数回调函数,也有自己的参数 -- onInvalidate。它也是一个函数,用于清除 effect 产生的副作用。

watchEffect<Type>(
(oninvalidate) => {
console.log('监听参数',)
oninvalidate(() => {
console.log('before')
})
}
)

oninvalidate 只作用于异步函数,只有两种情况才会被调用:

  • watchEffect 第一个参数 effect 回调函数,当 effect 被重新调用时。
  • 当监听器被注销时。

如何停止监听?

副作用是伴随组件加载而发生的,在组件卸载时,就需要清理这些副作用。watchEffect 的返回值依旧是一个函数,调用它的返回函数时就会清除监听,经常在组件被卸载时调用。

setup() {
const stop = watchEffect(() => {
/* ... */
});

// 调用之后,清除监听
stop();
}

2、watch

监听某个特定属性,并能够返回改变前后的值。使用语法:

watch(
name,//需要监听的源
(newVal, oldVal) => {}, //返回改变前后的值
options //可选配置项
)

在页面刚进入的时候并不会立即执行,只有监听的源数据改变时才会执行。可以监听的源数据可以是一个也可以是多个。

示例如下:

<template>
<div>
<input v-model="msg" />
<input v-model="str" />
</div>
</template>
<script lang="ts" setup>
import { ref, reactive, watchEffect, watch } from 'vue'
let msg: string = ref('')
let str: string = ref('')
/* 监听一个源: */
watch(msg, (newVal, oldVal) => {
console.log('newVal', newVal)
console.log('oldVal', oldVal)
})
/* 监听多个源: */
watch([msg, str], (newVal, oldVal) => {
console.log('newVal', newVal)//返回一个数组
console.log('oldVal', oldVal)//返回一个数组
})
</script>

如果 watch 监听一个 ref 定义深层数据,修改值的时候会被监听到吗?

let nav: any = ref({
bar: {
name: 'menu',
},
})
watch(
nav,
(newV, oldV) => {
console.log('newV', newV)
}
)

当我们修改 nav.bar.name 的属性值的时候,发现监听内的回调函数并没有执行。此时如何解决该问题呢?

watch 函数还有一个 可选的 options 参数,它的配置项有:

  • deep 表示是否深度监听,是 boolean 值 ,默认是 false 。
  • immediate 是否立即执行。

解决 watch 无法深层监听 ref 方法1:添加 deep 配置项

let nav: any = ref({
bar: {
name: 'menu',
},
})
watch(nav, (newV, oldV) => {
console.log('newV', newV)
},
{
deep:true
}
)

解决 watch 无法深层监听 ref 方法2:ref 替换成 reactive

let nav: any = reactive({
bar: {
name: '11',
},
menu: {
name: '22',
},
})
watch(nav, (newV, oldV) => {
console.log('newV', newV.bar.name)
console.log('newV', newV.menu.name)
})

使用 reactive 监听深层对象开启和不开启 deep 效果是一样的。修改 nav.bar.name 或 nav.menu.name 的时候,都会触发函数。如果我们只是想监听其中一个属性该如何处理呢?

监听 reactive 单一值

let nav: any = reactive({
bar: {
name: '1',
},
menu: {
name: '2',
},
})
watch(
() => nav.bar.name,
(newV, oldV) => {
console.log('newV', newV)
},
)

3、computed

计算属性就是当依赖的属性值发生改变的时候,才会触发它的更改,如果依赖的值不发生改变,使用的是缓存中的值。

函数形式使用语法:

import { computed, ref } from "vue"
let num: number = ref(0)
const res: number = computed((): number => {
return num.value * 10
})

对象形式使用语法:

import { computed, ref } from "vue"
let num: number = ref(0)
const res: number = computed({
get: (): number => {
return num.value * 10
},
set: (val: number): number => {
num.value = val / 10
},
})

使用 computed 实现购物车价格计算功能,代码:

<template>
<table border width="800">
<thead>
<tr>
<th>序号</th>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in shopList" :key="index">
<td>{{ index + 1 }}</td>
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td>
<button @click="oprationNum(item, false)">-</button>
{{ item.num }}
<button @click="oprationNum(item, true)">+</button>
</td>
<td>
<button @click="delShop(index)">删除</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" align="right">总价:{{ totalPrice }}</td>
</tr>
</tfoot>
</table>
{{ shopList }}
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
interface Shopping {
name: string
price: number
num: number
}
let shopList: Array<Shopping> = reactive([
{ name: '百香果奶茶', price: 28, num: 1 },
{ name: '优乐美奶茶', price: 4.5, num: 1 },
{ name: '提子饼干', price: 12, num: 1 },
])
const oprationNum = (item: Shopping, type: boolean): void => {
if (item.num < 99 && type) {
item.num++
} else if (item.num > 1 && !type) {
item.num--
}
}
const delShop = (index: number): void => {
shopList.splice(index, 1)
}
const totalPrice: number = computed((): number => {
return shopList.reduce((prev, next) => {
return prev + next.price * next.num
}, 0)
})
</script>
责任编辑:姜华 来源: 今日头条
相关推荐

2022-06-09 08:28:27

Vue3watchwatchEffec

2021-12-07 05:44:45

Vue 3 Watch WatchEffect

2022-06-26 00:00:02

Vue3响应式系统

2021-12-08 09:09:33

Vue 3 Computed Vue2

2021-05-12 10:25:29

开发技能代码

2021-01-15 08:10:26

Vue开发模板

2023-11-28 17:49:51

watch​computed​性能

2023-12-11 07:34:37

Computed计算属性Vue3

2021-05-12 10:25:53

组件验证漏洞

2023-12-14 08:25:14

WatchVue.js监听数据

2021-08-11 08:31:42

前端技术Vue3

2024-01-04 08:38:21

Vue3API慎用

2024-04-16 12:05:27

Vue3前端

2021-12-01 08:11:44

Vue3 插件Vue应用

2021-11-30 08:19:43

Vue3 插件Vue应用

2023-11-28 09:03:59

Vue.jsJavaScript

2021-04-22 07:49:51

Vue3Vue2.xVue3.x

2024-03-08 10:38:07

Vue响应式数据

2020-09-19 21:15:26

Composition

2021-12-02 05:50:35

Vue3 插件Vue应用
点赞
收藏

51CTO技术栈公众号