vuejs-challenges icon indicating copy to clipboard operation
vuejs-challenges copied to clipboard

19 - 切换焦点指令

Open ChenHaoJie9527 opened this issue 3 years ago • 0 comments

// 你的答案
<script setup lang="ts">
import { ref, Ref } from 'vue';

const state = ref(true);

/**
 * Implement the custom directive
 * Make sure the input element focuses/blurs when the 'state' is toggled
 *
 */

const VFocus = {
  mounted(el: any, binding: { value: any }, vnode: any, prevVnode: any) {
    const input = el;
    const res: Ref<any> = ref(binding.value);
    if (res.value) {
      input.focus();
    }
  },
  updated(el: any, binding: { value: any }, vnode: any, prevVnode: any) {
    const input: HTMLInputElement = el;
    const res: Ref<any> = ref(binding.value);
    if (res.value) {
      input.focus();
    } else {
      input.blur();
    }
  },
};

setInterval(() => {
  state.value = !state.value;
}, 2000);
</script>

<template>
  <input v-focus="state" type="text" />
</template>

ChenHaoJie9527 avatar Aug 05 '22 07:08 ChenHaoJie9527

为什么可以触发updated.

abigmiu avatar Aug 22 '22 02:08 abigmiu

updated

是因为vnode里面包含了state这个状态?

abigmiu avatar Aug 22 '22 02:08 abigmiu