Skip to content

DOM 变动观察者

The v-mutate 指令使用了 Mutation Observer API。它为检测 DOM 元素更改提供了简单易用的接口。

使用

v-mutateMutation Observer API的一个简单接口 它是用Vue directives实现的 . 有两种主要方法可以改变v-mutate的选项;使用句点表示法的指令修饰符,或使用自定义选项对象。下表包含可用指令修饰符的信息:

限定词默认值描述
.attrtrueattr 限定于目标节点的属性变更
.chartrueThe char modifier 监视对目标节点字符数据的更改(如果.subtrue,则监视其后代)
.childtrueThe child modifier 监视子节点的添加或删除 (如果.subtrue,则监视其后代)
.subtrueThe sub modifier 将所有监视扩展到目标节点的整个子树
.onceundefinedThe once modifier 调用用户提供的回调一次,并断开观察者的连接
.immediateundefinedThe immediate modifier 在 mounted 时调用用户提供的回调,不影响 .once

默认情况下, v-mutate 启用 .attr, .char, .child, 和 .sub ,除非你手动应用了其中一个;在这种情况下,未定义选项被设置为 false:

html
<template>
  <div>
    <!-- attr, char, child, and sub are true -->
    <div v-mutate="..." />

    <!-- child is true, attr, char, and child are false -->
    <div v-mutate.child="...">
  </div>
</template>

除了 modifier (修饰)符语法之外,v-mutate 指令还可以通过包含handler(处理程序)和options(选项)键的自定义对象进行配置。下面的例子演示了两个进程如何实现相同的结果:

html
<template>
  <div>
    <div
      v-mutate="{
      handler: onMutate,
        modifiers: {
          child: true,
          sub: true,
        }
      }"
    />

    <!-- is the same as -->

    <div v-mutate.child.sub="onMutate" />
  </div>
</template>

<script setup>
  function onMutate() {
    //
  }
</script>

WARNING

当使用自定义选项时,建议使用.sub修饰符。这将突变监控扩展到目标元素的所有后代。

Once (一次)

有时你的回调应该只触发一次。在这些场景中,使用once选项在第一次检测到突变后断开观察者的连接。在下一个示例中,我们将数据值内容 content (绑定)到 2 个单独的v-card 组件和一个input(输入);然后跟踪我们输入时发生的突变数量:

html
<template>
  <div>
    <input type="text" v-model="content" />

    <v-card v-mutate="onMutate">{{ content }}</v-card>

    <v-card v-mutate.once="onMutate">{{ content }}</v-card>
  </div>
</template>

<script setup>
  import { onMounted, shallowRef } from "vue";

  const content = shallowRef("Foo");
  const mutations = shallowRef(0);

  onMounted(() => {
    content.value = "Bar";

    console.log(mutations.value); // 2

    setTimeout(() => {
      content.value = "Foobar";

      console.log(mutations.value); // 3
    }, 200);
  });

  function onMutate() {
    mutations.value++;
  }
</script>

当内容的值发生变化时,两张卡片都会立即调用 onMutate 并迭代 mutations (变化)数据值的值。因为第二张卡片使用了once修饰符,所以在 content (满足)了第一次更改内容操作后,它会自动解除绑定它的观察者。

Immediate (即时的)

不像Intersection Observer API ,在创建 Mutation Observer(突变观察者)时不会立即调用所提供的回调。Vuetify 使用immediate选项将此行为规范化。在下面的例子中,v-mutate指令在元素最初加载到 DOM 中时调用 onMutate 方法,并且根据提供的选项,每次加载都有 mutation(突变)。

html
<template>
  <div v-mutate.immediate="onMutate">...</div>
</template>

<script setup>
  import { onMounted, shallowRef } from "vue";

  const mutations = shallowRef(0);

  onMounted(() => {
    console.log(mutations.value); // 1
  });

  function onMutate() {
    mutations.value++;
  }
</script>

INFO

immediate(立即的)回调不被计算为突变,并且在使用once(一次)时不会触发观察者断开连接。

API

指令描述
v-mutateDOM 变动观察者指令

Examples