6. Data verification plug-in

App.mixin is first used for verification

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>hello vue</title>
  <! Vue library -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  const app = Vue.createApp({
    data(){
      return{
        name: 'zibo'.age: 25}},rules: {
      age: {
        validate: age= > age > 25.message: "Too young!
      },
      name: {
        validate: name= > name.length > 4.message: "It's too short!}},template: ` 
       
name: {{name}} age: {{age}}
`
}); / / use mixins app.mixin({ // Execute after the instance is created created(){ / / traverse the rules for(let key in this.$options.rules){ // Fetch the current rule const item = this.$options.rules[key]; // Monitor key changes and execute the function this.$watch(key, value= > { // Execute the validate expression under each rule // value is the new value const result = item.validate(value); // Print the message in the rule if false is returned if(! result){console.log(item.message); }}); }}});const vm = app.mount('#root');
</script> </html> Copy the code

The results

Through plug-ins

<! DOCTYPEhtml>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <title>hello vue</title>
  <! Vue library -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  const app = Vue.createApp({
    data(){
      return{
        name: 'zibo'.age: 25}},rules: {
      age: {
        validate: age= > age > 25.message: "Too young!
      },
      name: {
        validate: name= > name.length > 4.message: "It's too short!}},template: ` 
       
name: {{name}} age: {{age}}
`
}); // Define a plug-in: new form, equivalent to writing install const validatorPlugin = (app, options) = > { / / use mixins app.mixin({ // Execute after the instance is created created(){ / / traverse the rules for(let key in this.$options.rules){ // Fetch the current rule const item = this.$options.rules[key]; // Monitor key changes and execute the function this.$watch(key, value= > { // Execute the validate expression under each rule // value is the new value const result = item.validate(value); // Print the message in the rule if false is returned if(! result){console.log(item.message); }}); }}}); }// Use plugins app.use(validatorPlugin); const vm = app.mount('#root');
</script> </html> Copy the code

The results