1.在components
目录下新建一个validate.js:
export default{
install(Vue){
Vue.prototype.$myName = "zhagngsan";
}
}
这就是我们的插件,定义了一个属性
2.入口文件jssrc/index.js
加入:
// 引入
import validate from "./../components/validate";
// 使用
Vue.use(validate);
3.我们到user-username.vue
组件下验证一下:
mounted(){
alert(this.$myName);
},
浏览器访问登录页面,成功弹出:
4.刚刚我们已经学会插件里定义属性,马上来学一下如何定义方法:
export default{
install(Vue){
// Vue.prototype.$myName = "zhagngsan";
Vue.prototype.checkUserName = (value) => { if(/\w{6,20}/.test(value)){ return true; }else{ return false; } } } }
同样可以使用该方法:
if(this.checkUserName("hello")){
alert("ok"); }else{ alert("error"); }
5.
我们修改user-name.vue
组件,来实现文本框验证:
<template>
<div class="form-group"> <label class="col-sm-2 control-label">用户名</label> <div class="col-sm-10"> <input type="text" v-model="username" v-on:change="userNameChange" class="form-control" :placeholder="username"> <label class="label label-danger" v-if="showErrorLabel">用户不合法</label> </div> </div> </template> <script> export default{ props:["placeholder"], data:function () { return { username:"", showErrorLabel:false, } }, methods:{ userNameChange(){ // 用户名改变的方法里判断 用户名是否复合要求 if(this.checkUserName(this.username)){ this.showErrorLabel = false; // 如果验证没有通过就显示错误提示 }else{ this.showErrorLabel = true; } // 调用父组件的方法 this.$emit("childChange","username",this.username) } } } </script>
自定义指令
文档:https://vuefe.cn/guide/custom-directive.html
1、validate.js:
export default{
install(Vue){
// Vue.prototype.$myName = "zhagngsan";
Vue.prototype.checkUserName = (value) => { if(value == ""){ return true; // 如果没有填写,默认为true } if(/\w{6,20}/.test(value)){ return true; }else{ return false; } } Vue.directive("uname",{ bind(){ console.log("bind"); // 只会调用一次 }, update(el,binding,vnode){ console.log(el); console.log(binding); console.log(vnode); }, }) } }
2、我们自定了一个uname
指令,下面来看一下如何使用的?
<input type="text" v-uname="username" v-model="username" v-on:change="userNameChange" class="form-control" :placeholder="username">
我们在组件的模板里使用了 v-uname
,并且给绑定了”username”数据。
我们打开浏览器的控制台:
说明我们定义的指令里,这个方法执行了:
bind(){
console.log("bind"); // 只会调用一次
},
3、下面我们来看一下update
里的东东
update(el,binding,vnode){
console.log(el);
console.log(binding);
console.log(vnode);
}
我们这里只是一个简单的展示,一定要看文档熟悉
https://vuefe.cn/guide/custom-directive.html