前言
Vuex VueRouter都是插件。在调用这些插件的时候,发现都会调用Vue.use(myPlugin);
Vue.use(MyPlugin) 本质上是调用MyPlugin.install(Vue);
使用插件必须在new Vue()启动应用之前完成,实例化之前就要配置好;
如果使用Vue.use多次注册相同插件,那只会注册成功一次;
Vue.mixin
全局注册的mixin,会影响所有创建的Vue实例
- 同名钩子函数将合并为一个数组,混入对象的钩子将在组件自身钩子之前调用;
- 二者的methods、components和directives,将被合并为同一个对象。若对象键名冲突时,取组件对象的键值对;
需求
完成一个数据校验插件:
1、处理自定义rules规则;
2、这个rules需要一个对象;
3、该对象指定组件中的数据的验证规则;
新建一个dataValidatePlugin.js,内容为:
const RulesPlugin = {
install(Vue){
Vue.mixin({
created(){
const rules = this.$options.rules;
if(rules){
Object.keys(rules).forEach(key=>{
const{validate,message} = rules[key];
this.$watch(key,newValue=>{
const valid = validate(newValue);
if(!valid){
console.error(message);
}
});
});
}
}
});
}
}
再在页面中调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>数据校验插件</title>
<script src="../node_modules/vue/dist/vue.js"></script>
<script src="./dataValidatePlugin.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
Vue.use(RulesPlugin);
let vm = new Vue({
el:'#app',
data:{
number:1,
phone:'',
},
rules:{
number:{
validate:value=>value>0,
message:'number必须大于0'
},
phone:{
validate:value=>value.length === 11,
message:'电话号码数字必须是11位'
}
},
});
vm.number = 0;
</script>
</body>
</html>
在控制台通过vm.number=-1修改number的值可以看到控制台输出一条红色的错误信息。