Vue3的指令使用demo

如何定义指令?

import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)
// 派发自定义事件
const trigger = (el, type) => {
    const e = document.createEvent('HTMLEvents');
    e.initEvent(type, true, true);
    el.dispatchEvent(e);
}

app.directive('input', {
    mounted(el, binding) {
        const _type = binding.arg;

        el.$handler = (el) => {
            console.log(_type);
            switch(_type) {
                case 'number':
                    el.value = el.value.replace(/[^\d]/, '');
                    break;
                case 'decimal':
                    el.value = el.value.replace(/[^\d.]/g, '');
                    el.value = el.value.replace(/\.{2,}/g, '.');
                    break;
            }
            trigger(el, 'input');
        }
        el.$handler(el);
    },
    updated(el) {
        el.$handler && el.$handler(el)
    },
})

app.mount('#app')

如何使用指令

<template>
  <input v-input:number="inputValue" v-model="inputValue" />
</template>

<script lang='ts'>
import { defineComponent, ref } from "vue";
export default defineComponent({
  setup() {
    let inputValue = ref('')
    return {
      inputValue,
    };
  },
});
</script>

原文链接,我只是学习

https://juejin.cn/post/6968996649515515917#heading-9

暂无评论

发表评论

您的电子邮件地址不会被公开,必填项已用*标注。

相关推荐