Vue插件编写

写个插件

引用https://vuefe.cn/guide/plugins.html

1.在components 目录下新建一个validate.js:

1
2
3
4
5
export default{
install(Vue){
Vue.prototype.$myName = "zhagngsan";
}
}

这就是我们的插件,定义了一个属性

2.入口文件jssrc/index.js 加入:

1
2
3
4
// 引入
import validate from "./../components/validate";
// 使用
Vue.use(validate);

3.我们到user-username.vue 组件下验证一下:

1
2
3
mounted(){
alert(this.$myName);
},

浏览器成功弹出alert

4.刚刚我们已经学会插件里定义属性,马上来学一下如何定义方法:

1
2
3
4
5
6
7
8
9
10
11
12
export default{
install(Vue){
// Vue.prototype.$myName = "zhagngsan";
Vue.prototype.checkUserName = (value) => {
if(/\w{6,20}/.test(value)){
return true;
}else{
return false;
}
}
}
}

同样可以使用该方法:

1
2
3
4
5
if(this.checkUserName("hello")){
alert("ok");
}else{
alert("error");
}

我们修改user-name.vue 组件,来实现文本框验证:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<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

validate.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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 指令,下面来看一下如何使用的?

1
<input type="text" v-uname="username" v-model="username" v-on:change="userNameChange" class="form-control" :placeholder="username">

我们在组件的模板里使用了 v-uname ,并且给绑定了”username”数据。

我们打开浏览器的控制台:
> bind

说明我们定义的指令里,这个方法执行了:

1
2
3
bind(){
console.log("bind"); // 只会调用一次
},

3.下面我们来看一下update 里的东东

1
2
3
4
5
update(el,binding,vnode){
console.log(el);
console.log(binding);
console.log(vnode);
}

引用文档https://vuefe.cn/guide/custom-directive.html

© 2018 Qing的前端开发Blog All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero