preface
Vuex VueRouter are plugins. When these plug-ins are called, vue.use (myPlugin) is called; Use (MyPlugin) essentially calls myplugin. install(Vue); Using plug-ins must be done before new Vue() starts the application and configured before instantiation; If you use vue. use to register the same plug-in multiple times, the registration will be successful only once.
Vue.mixin
Globally registered mixins affect all created Vue instances
- The hook function of the same name is merged into an array, and the hooks mixed with the object are called before the component’s own hooks;
- The methods, Components, and directives of both will be combined into the same object. If the object key name conflicts, take the key value pair of the component object.
demand
Complete a data validation plugin: 1. Handle custom rules; 2. This rule requires an object. 3. This object specifies the validation rules for the data in the component.
Create a new datavalidateplugin.js with the following contents:
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); }}); }); }}}); }}Copy the code
Call it on the page
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, <meta http-equiv=" x-UA-compatible "content="ie=edge"> <title> /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 must be greater than 0'}, phone:{validate:value=>value.length === = 11, message:'number must be 11 '}},}); vm.number = 0; </script> </body> </html>Copy the code
If you change the value of number on the console with vm.number=-1, you can see the console output a red error message.