Skip to content

Commit 3cbec70

Browse files
authored
doc: Update vue.md (#786)
添加 vue3 watch 监听多个值的模板
1 parent 8e9132f commit 3cbec70

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

docs/vue.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,44 @@ watch(count, function() {
510510
```
511511
<!--rehype:className=wrap-text-->
512512

513+
### 监听多个值
514+
<!--rehype:wrap-class=col-span-2-->
515+
516+
```html
517+
<template>
518+
<h1> {{ count1 }} </h1>
519+
<h1> {{ count2 }} </h1>
520+
<button @click="count1++">count1</button>
521+
<button @click="count2++">count2</button>
522+
</template>
523+
524+
<script setup>
525+
import { watch, ref } from 'vue';
526+
527+
const count1 = ref(0)
528+
const count2 = ref(0)
529+
530+
watch(
531+
// 监听的表达式或函数
532+
() => ({
533+
count1: count1.value,
534+
count2: count2.value
535+
}),
536+
// 回调函数
537+
(newValue, oldValue) => {
538+
// 在这里执行需要的逻辑
539+
console.log('count1 或 count2 变化了:', newValue);
540+
},
541+
// immediate: true 表示在初始渲染时立即执行一次回调函数,以便处理初始的状态。
542+
// deep: true 表示深度监听,即对 newValue 和 oldValue 进行深层比较,而不是简单的引用比较。
543+
{ immediate: true, deep: true }
544+
);
545+
</script>
546+
547+
<style scoped>
548+
</style>
549+
```
550+
513551
### 计算状态
514552
<!--rehype:wrap-class=col-span-2-->
515553

0 commit comments

Comments
 (0)