1. components
Create a new validate.js in the directory:
export default{
install(Vue){
Vue.prototype.$myName = "zhagngsan";
}
}
This is our plugin, defining a property
2. The entry file is jssrc/index.js
added:
// 引入
import validate from "./../components/validate";
// 使用
Vue.use(validate);
3. Let's go to the user-username.vue
component to verify:
mounted(){
alert(this.$myName);
},
The browser accesses the login page and successfully pops up:
4. We have just learned to define attributes in the plugin, let's learn how to define methods:
export default{
install(Vue){
// Vue.prototype.$myName = "zhagngsan";
Vue.prototype.checkUserName = (value) => { if(/\w{6,20}/.test(value)){ return true; }else{ return false; } } } }
You can also use this method:
if(this.checkUserName("hello")){
alert("ok"); }else{ alert("error"); }
5.
We modify the user-name.vue
component to implement text box validation:
<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>
custom directive
Documentation: 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. We have customized a uname
command, let's see how to use it?
<input type="text" v-uname="username" v-model="username" v-on:change="userNameChange" class="form-control" :placeholder="username">
We use it in the template of the component v-uname
and bind the "username" data to it.
We open the browser's console:
this method is executed in the instruction we defined:
bind(){
console.log("bind"); // 只会调用一次
},
3. Let's take a look at what update
's inside
update(el,binding,vnode){
console.log(el);
console.log(binding);
console.log(vnode);
}
We are just a simple display here, be sure to read the documentation to be familiar with
https://vuefe.cn/guide/custom-directive.html