vue 引入全局公共方法

Vue2年前 (2022)发布 小马大哥哥
1K 0 0

在项目中, 每次添加一个公共方法, 都需要main.js中引入, 或某些页面单独引入, 让我因为不能装b而烦恼

  • 在公共js随意添加方法
  • 一次设置, 无需再main.js一次次引入
  • 页面中如何使用 this.methods()

用法


<!--common.js-->
export default {
    install(Vue,options){
        Vue.prototype.methods1 = () => {},
        Vue.prototype.methods2 = () => {}
    }
}

复制代码
<!--main.js-->
import comm form './assets/js/commen'
Vue.use(comm)
复制代码
<!--pages-->
this.methos1()
this.methos2()
复制代码

以 Elemen-ui 表单验证公用js为例


<!--verify.js-->
export default {
    install(Vue, options) {
        <!--手机号验证-->
        Vue.prototype.verify_checkPhone = (tipInfo = '请输入正确号码') => {
            return (rule, value, callback) => {
                const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
                if (!value || reg.test(value)) {
                    callback();
                } else {
                    return callback(new Error(tipInfo));
                }
            }
        },
        <!--IP验证-->
        Vue.prototype.verify_IP = (tipInfo = '请输入有效的IP值') => {
		    return (rule, value, callback) => {
		        // 需要验证空值
		        // if (isYzNull && !value) return callback(new Error('手机号不能为空'))
		        // 校验IP地址格式
		        const reg = /^(?:(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:1[0-9][0-9]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:2[0-4][0-9])|(?:25[0-5])|(?:1[0-9][0-9])|(?:[1-9][0-9])|(?:[0-9]))$/
		        if (!value || reg.test(value)) {
		            callback();
		        } else {
		            return callback(new Error(tipInfo));
		        }
		    }
		}
    }
} 
复制代码
<!--main.js-->
import formCheck from './assets/js/verify.js'
Vue.use(formCheck)
复制代码
<!--MProj.vue-->
data() {
    return {
        rules: {
            param5: [
                { validator: this.verify_checkPhone(), trigger: ["blur", "change"]  }
            ],
            param6: [
                { validator: this.verify_IP(), trigger: ["blur", "change"]  }
            ]
        }
    }
}

原文链接:https://juejin.cn/post/6844903962068385806

© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...