Misael
Misael

Reputation: 123

How can I access modelValue from inside a direct in Vue 3

The question is: How to access el.modelValue and update it from custom directive?

directives: {
    currency: {
      mounted(el, binding, vnode, prevVnode) {
        console.log(vnode, prevVnode)

        el.oninput = (e) => {
          if (Number.isNaN(e.data)) return

          el.value = e.data

          e.oninput = () => {
            binding.value += 1
          }
        }
      },
    },

Upvotes: 1

Views: 749

Answers (1)

Vissie
Vissie

Reputation: 777

For reading, if you want to be sure that the value of the v-model is used instead of the value of the input (as they can differ) you could set the variable that is used for the v-model as directive value. As of mutating, you should dispatch the appropriate event to the element and let Vue handle the update of the v-model. Like in this example below:

StackBlitz

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

<script setup lang="ts">
import { ref } from 'vue';

const value = ref('some string');

function patchInputValue(el, value) {
  var event = new Event('input', { bubbles: true });
  el.value = value;
  el.dispatchEvent(event);
}

const vFocus = {
  mounted: (el, binding) => {
    // binding.value -> 'some string'
    patchInputValue(el, 'new value');
  },
};
</script>

Note that new Event() won't work in IE <11. There are a couple of polyfill packages that provide compatibility.

Upvotes: 1

Related Questions