Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端 - 自定义指令如何修改v-model绑定的值 - 个人文章 - SegmentFault 思否 #86

Open
HenryTSZ opened this issue Oct 18, 2023 · 0 comments

Comments

@HenryTSZ
Copy link
Owner

HenryTSZ commented Oct 18, 2023

https://segmentfault.com/a/1190000022753905

今天想做这样一件事:给input添加验证功能
本来是想做成能依赖正则表达式实时修正的(很尴尬 没整出来)
结果就只能做成blur后再验证 然后验证没过就清空
听着很简单 其实奥妙的很 上代码
.vue

<input type="text" v-model="mobile" v-validate="'手机号'" />

directive.js

import Vue from 'vue'

const validate = {
    '手机号': function (s) {
        return /^1[0-9]{10}$/.test(s)
    }
}
Vue.directive('validate', {
    bind: function (el, binding, vnode) {
        const key = binding.value
        const isMobile = validate[key]
        el.addEventListener('blur', function () {
            if (!isMobile(this.value)) {
                this.value = ''
                el.dispatchEvent(new Event('input')) // 这个是点睛之笔
                alert(`${key}格式不正确`)
            }
        })
    }
})

如果没写这句**el.dispatchEvent(new Event('input'))** 单单写了this.value = '' 虽说页面效果是有了 但其实data里定义的mobile是没变的
那为什么写了这句**el.dispatchEvent(new Event('input'))**就可以改变data里定义的mobile呢?
原因是因为v-model就是一个语法糖

<input type="text" v-model="mobile" v-validate="'手机号'" /\> 
<input type="text" :value="mobile" @input="mobile = $event.target.value" />

上面两句是等价的
所以想真正的改变data里定义的mobile 就需要手动触发input事件 才可以执行这句mobile = $event.target.value 才能真正的达到效果
基本就这样

如果要实时修正,就需要监听 input 事件:el.addEventListener('input', ...)

那就不能使用 el.dispatchEvent(new Event('input')),会进入无限循环中

如果是给一个组件绑定的自定义事件,可以通过 vnode 找到该组件,触发 $emit 也可以,具体代码:

vnode.componentInstance.$emit('input', newValue)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant