实现对各个组件进行校验
mixins
hots
rendless (推荐)
1.app中引入
<template> <div id="app"> <task-list/> </div> </template> <script> import taskList from ‘../src/views/taskList‘ export default { name: ‘App‘, components: { taskList } } </script> <style> </style>
2. 添加校验的组件input,textarea,通过SValidate子组件来实现校验,taskList组件
<template> <div> <s-validate #default="{ validate }" :value="value" :rules="rules"> <input @blur="validate" v-model="value"/> </s-validate> <s-validate #default="{ validate }" :value="value" :rules="textRules"> <textarea type="text" @blur="validate" v-model="text"/> </s-validate> </div> </template> <script> import SValidate from ‘./SValidate‘ export default { name: ‘TestBody‘, data () { return { value: ‘hi‘, text: ‘hi‘, rules: [ { test: function (value) { return /\d+/.test(value) }, message: ‘请输入一个数字‘ } ], textRules: [ { test: function (value) { return value }, message: ‘请输入一个非空的值‘ } ] } }, components: { SValidate } } </script> <style lang="scss" scoped> </style>
3.子组件校验工作
<template> <div> <slot :validate="validate"></slot> {{ errMsg }} </div> </template> <script> export default { props: ["value", "rules"], data() { return { errMsg: "" }; }, methods: { validate() { let validate = this.rules.reduce((pre, cur) => { let check = cur && cur.test && cur.test(this.value); this.errMsg = check ? "" : cur.message; return pre && check; }, true); return validate; } } }; </script>
4.实现效果:
原文:https://www.cnblogs.com/TheYouth/p/14429504.html